package com.bsoft.gol.hcs.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bsoft.gol.hcs.base.BaseRequest;
import com.bsoft.gol.hcs.common.service.BaseDataService;
import com.bsoft.gol.hcs.constants.HospitalVisitRecordTaskConstants;
import com.bsoft.gol.hcs.enumcase.DiagnosisAndTreatmentDataTypeEnum;
import com.bsoft.gol.hcs.enumcase.DiseaseCollectConditionEnum;
import com.bsoft.gol.hcs.enumcase.RuleConditionTypeEnum;
import com.bsoft.gol.hcs.his.bean.request.PushMessageRequest;
import com.bsoft.gol.hcs.his.service.SendMsgService;
import com.bsoft.gol.hcs.satisfaction.dao.SurgicalTypeDAO;
import com.bsoft.gol.hcs.satisfaction.entity.SurgicalType;
import com.bsoft.gol.hcs.specialist.bean.request.AddExecutionListRequest;
import com.bsoft.gol.hcs.specialist.bean.request.PatientSearchRuleRequest;
import com.bsoft.gol.hcs.specialist.bean.response.ListPatientSearchRuleResponse;
import com.bsoft.gol.hcs.specialist.bean.response.ListSubscribeResponse;
import com.bsoft.gol.hcs.specialist.bean.response.QueryDiseaseTypeResponse;
import com.bsoft.gol.hcs.specialist.dao.*;
import com.bsoft.gol.hcs.specialist.entity.*;
import com.bsoft.gol.hcs.specialist.service.IDiseaseSpeciesService;
import com.bsoft.gol.hcs.specialist.service.IFollowUpPlanService;
import com.bsoft.gol.hcs.specialist.service.IPatientSearchRuleExecuteService;
import com.bsoft.gol.hcs.task.bean.request.*;
import com.bsoft.gol.hcs.task.bean.response.*;
import com.bsoft.gol.hcs.utils.*;
import com.bsoft.gol.hcs.visitrecord.bean.vo.*;
import com.bsoft.gol.hcs.visitrecord.dao.*;
import com.bsoft.gol.hcs.visitrecord.entity.*;
import com.google.common.collect.Lists;
import ctd.controller.exception.ControllerException;
import ctd.job.annotation.ScheduleJob;
import ctd.job.pojo.JobParameter;
import ctd.persistence.annotation.DAOTransaction;
import ctd.persistence.exception.DAOException;
import ctd.util.BeanUtils;
import ctd.util.JSONUtils;
import ctd.util.context.ContextUtils;
import hcn.base.BasePropertyConfig;
import hcn.base.VrOutpatientVisitRecord;
import hcn.base.notification.event.NotificationEvent;
import hcn.enums.MsgTemplateCode;
import hcn.enums.PlatFormServiceEnum;
import hcn.service.commonClinical.qo.ParamsOrgQo;
import hcn.specialist.DiseaseSpecies;
import hcn.util.BaseResponse;
import hcn.util.ResultCode;
import io.minio.Xml;
import org.apache.commons.lang3.StringUtils;
import org.atag.sysrouter.model.his.HisXmlHeader;
import org.atag.sysrouter.model.his.HisXmlRequest;
import org.atag.sysrouter.service.ServiceController;
import org.atag.util.http.KdHttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import service.rpc.BasePropertyConfigIntf;
import service.rpc.IServiceOpenRpcService;
import org.atag.util.common.SpringPropertiesUtil;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.bsoft.gol.hcs.utils.WhisClientUtil.*;


/**
 * 医院门诊、住院、检验申请、检查申请、治疗记录、取药记录、手术记录
 * Created by ChenJij on 2020/7/21.
 */
@Component
public class HospitalVisitsRecordTask {
    private static final Logger logger = LoggerFactory.getLogger(HospitalVisitsRecordTask.class);
    @Value("${phis_path_url}")
    public String PHIS_PATH_URL;
    @Autowired
    IDiseaseSpeciesService diseaseSpeciesService;
    @Autowired
    PatientMedicalDataCollectDAO patientMedicalDataCollectDAO;
    @Autowired
    FusTeamChronicGroupRecordDAO fusTeamChronicGroupRecordDAO;
    @Resource(name = "followUpPlanService")
    IFollowUpPlanService followUpPlanService;
    @Autowired
    TreatmentRecordDAO treatmentRecordDAO;
    @Autowired
    IServiceOpenRpcService serviceOpenRpcService;
    @Autowired
    PrescriptionRecordDAO prescriptionRecordDAO;
    @Autowired
    ExamReportDAO examReportDAO;
    @Autowired
    InspectReportRecordDAO inspectReportRecordDAO;
    @Autowired
    InspectReportRoutineDetailDAO inspectReportRoutineDetailDAO;
    @Autowired
    InspectReportMicrobeResultDAO inspectReportMicrobeResultDAO;
    @Autowired
    InspectReportMicrobeRecordDAO inspectReportMicrobeRecordDAO;
    @Autowired
    ExamReportImageDAO examReportImageDAO;
    @Autowired
    FollowUpRecordsDAO followUpRecordsDAO;
    @Autowired
    PatientSearchRuleDAO patientSearchRuleDAO;
    @Autowired
    private BaseDataService baseDataService;
    @Autowired
    private VrOutpatientVisitRecordDAO vrOutpatientVisitRecordDAO;
    @Autowired
    private VrApplicationFormDetailDAO vrApplicationFormDetailDAO;
    @Autowired
    private VrApplicationFormRecordDAO vrApplicationFormRecordDAO;
    @Autowired
    private VrDispensingRecordDAO vrDispensingRecordDAO;
    @Autowired
    private VrInpatientVisitRecordDAO vrInpatientVisitRecordDAO;
    @Autowired
    private VrSurgicalRecordDAO vrSurgicalRecordDAO;
    @Autowired
    private VrVisitDiagnosisDAO vrVisitDiagnosisDAO;
    @Autowired
    private SurgicalTypeDAO surgicalTypeDAO;
    @Resource(name = "patientSearchRuleExecuteService")
    private IPatientSearchRuleExecuteService patientSearchRuleExecuteService;
    @Autowired
    private SendMsgService sendMsgService;
    private String type;
    @Value("${project_source}")
    private String proSource;
    @Value("${admin_user_id}")
    private String adminUserId;
    //his数据同步任务执行dao
    @Autowired
    private DataSyncScheduledInfoDAO dataSyncScheduledInfoDAO;
    @Autowired
    private VrSynchroSettingsDAO vrSynchroSettingsDAO;
    @Autowired
    private PatientSearchRuleDetailDAO patientSearchRuleDetailDAO;
    @Autowired
    BasePropertyConfigIntf basePropertyConfigService;


    /**
     * 同步his数据同步任务执行
     */
    @ScheduleJob(jobName = "syncDataScheduledInfo", cron = "0 0 22 * * ?", shardingTotalCount = 1, description =
            "his数据同步任务生成", overwrite = true)
    public void syncDataScheduledInfo(JobParameter jobParameter) throws Exception {
        logger.info("开始执行his数据同步任务生成定时任务…………");
        try {
            //1.获取同步任务参数设置信息列表
            List<VrSynchroSettings> synchroSettingsList = vrSynchroSettingsDAO.queryVrSynchroSettingsList();
            if (CommonUtils.isNotEmpty(synchroSettingsList)) {
                for (VrSynchroSettings vrSynchroSettings : synchroSettingsList) {
                    //2.出现当前设置初始化数据起始时间是否已经生成了任务
                    String time = DateUtil.formDate(vrSynchroSettings.getBeginTime(), HospitalVisitRecordTaskConstants.DATA_FORMAT);
                    DataSyncScheduledInfo scheduledInfo = dataSyncScheduledInfoDAO.getDataSyncScheduledInfo(time, vrSynchroSettings.getOrgId(), vrSynchroSettings.getId());
                    int scheduledTotal;
                    Date nowDate = new Date();
                    Calendar calendar = Calendar.getInstance();
                    calendar.set(Calendar.HOUR_OF_DAY, 0);
                    calendar.set(Calendar.MINUTE, 0);
                    calendar.set(Calendar.SECOND, 0);
                    if (CommonUtils.isNotEmpty(scheduledInfo)) {
                        //2.1.已经生成了任务，则新生成任务开始时间从当前时间开始向后+90天
                        scheduledTotal = 90;
                        calendar.setTime(nowDate);
                    } else {
                        //2.2.没有生成任务，则从初始化数据起始时间到当前时间向后加90天
                        Integer timeMillis = DateUtils.getDaysByCountTimeMillis(vrSynchroSettings.getBeginTime(), nowDate);
                        scheduledTotal = 90 + timeMillis;
                        calendar.setTime(vrSynchroSettings.getBeginTime());
                    }
                    //3.执行任务数据的保存
                    for (int i = 0; i <= scheduledTotal; i++) {
                        String date = DateUtil.formDate(calendar.getTime(), HospitalVisitRecordTaskConstants.DATA_FORMAT);
                        DataSyncScheduledInfo syncScheduledInfo = dataSyncScheduledInfoDAO.getDataSyncScheduledInfo(date, vrSynchroSettings.getOrgId(), vrSynchroSettings.getId());
                        if (CommonUtils.isNotEmpty(syncScheduledInfo)) {//日期加一天
                            calendar.add(Calendar.DAY_OF_YEAR, 1);
                            continue;
                        } else {
                            DataSyncScheduledInfo dataSyncScheduledInfo = new DataSyncScheduledInfo();
                            dataSyncScheduledInfo.setTime(date);
                            dataSyncScheduledInfo.setOrgId(vrSynchroSettings.getOrgId());
                            dataSyncScheduledInfo.setType(vrSynchroSettings.getId());
                            dataSyncScheduledInfo.setStatus("0");
                            dataSyncScheduledInfo.setCreateTime(new Date());
                            //保存执行任务数据
                            dataSyncScheduledInfoDAO.save(dataSyncScheduledInfo);
                        }
                        //日期加一天
                        calendar.add(Calendar.DAY_OF_YEAR, 1);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("执行his数据同步任务生成定时任务失败：" + e.getMessage());
        }
        logger.info("开始执行his数据同步任务生成定时任务结束…………");
    }

    /**
     * 1-定时同步门诊数据           0 0 * * * ? 每两个小时执行一次
     */
    @ScheduleJob(jobName = "syncOutpatientRecords", cron = "0 0 18 * * ?", shardingTotalCount = 1, description =
            "his数据同步 门诊数据", overwrite = true)
    public void syncOutpatientRecords(JobParameter jobParameter) {
        logger.info("开始同步门诊记录" +new Date());
        commonSyncHisRecords(DiagnosisAndTreatmentDataTypeEnum.OUTPATIENT_RECORDS.getType());
    }

    /**
     * 2-定时同步住院数据     0 0 12 * * ?
     */
    @ScheduleJob(jobName = "syncInpatientVisitRecords", cron = "0 0 18 * * ?", shardingTotalCount = 1, description =
            "his数据同步 住院数据", overwrite = true)
    public void syncInpatientVisitRecords(JobParameter jobParameter) {
        commonSyncHisRecords(DiagnosisAndTreatmentDataTypeEnum.HOSPITALIZATION_RECORDS.getType());
    }

    /**
     * 3-定时同步体检记录
     */
    public void syncPhysicalExaminationRecords() {
        commonSyncHisRecords(DiagnosisAndTreatmentDataTypeEnum.PHYSICAL_EXAMINATION_RECORDS.getType());
    }

    /**
     * 4-定时同步检验报告
     */
    @ScheduleJob(jobName = "syncInspectReportRecords", cron = "0 0 * * * ?", shardingTotalCount = 1, description =
            "his数据同步 检验报告数据", overwrite = true)
    public void syncInspectReportRecords(JobParameter jobParameter) {
        commonSyncHisRecords(DiagnosisAndTreatmentDataTypeEnum.INSPECTION_REPORT.getType());
    }

    /**
     * 5-定时同步检查报告
     */
    @ScheduleJob(jobName = "syncCheckReportRecords", cron = "0 0 * * * ?", shardingTotalCount = 1, description =
            "his数据同步 检查报告数据", overwrite = true)
    public void syncCheckReportRecords(JobParameter jobParameter) {
        commonSyncHisRecords(DiagnosisAndTreatmentDataTypeEnum.CHECK_REPORT.getType());
    }

    /**
     * 6-定时同步病理报告
     */
    public void syncPathologicalReportRecords() {
        commonSyncHisRecords(DiagnosisAndTreatmentDataTypeEnum.PATHOLOGICAL_REPORT.getType());
    }

    /**
     * 7-定时同步电子病历
     */
    public void syncElectronicMedicalRecords() {
        commonSyncHisRecords(DiagnosisAndTreatmentDataTypeEnum.ELECTRONIC_MEDICAL_RECORD.getType());
    }

    /**
     * 8-定时同步医嘱记录
     */
    @ScheduleJob(jobName = "syncOrderRecords", cron = "0 0 * * * ?", shardingTotalCount = 1, description =
            "his数据同步 医嘱记录数据", overwrite = true)
    public void syncOrderRecords(JobParameter jobParameter) {
        commonSyncHisRecords(DiagnosisAndTreatmentDataTypeEnum.ORDER_RECORD.getType());
    }

    /**
     * 9-定时同步手术记录
     */
    @ScheduleJob(jobName = "syncVrSurgicalRecords", cron = "0 0 * * * ?", shardingTotalCount = 1, description =
            "his数据同步 手术记录数据", overwrite = true)
    public void syncVrSurgicalRecords(JobParameter jobParameter) {
        commonSyncHisRecords(DiagnosisAndTreatmentDataTypeEnum.SURGICAL_RECORDS.getType());
    }

    /**
     * 根据类型查询his数据公用方法
     *
     * @param type
     */
    private void commonSyncHisRecords(Integer type) {
        String strDate = DateUtils.dateFormate(new Date(), HospitalVisitRecordTaskConstants.DATA_FORMAT);
        //2.查询执行任务记录信息
        logger.info("开始时间"+strDate);
        List<DataSyncScheduledInfo> syncScheduledInfos = dataSyncScheduledInfoDAO.queryDataSyncScheduledInfoList(strDate, type);
        logger.info("查询执行记录信息"+syncScheduledInfos.size());
        if (CommonUtils.isNotEmpty(syncScheduledInfos)) {
            String beginDate = "";
            String endDate = "";
            for (DataSyncScheduledInfo dataSyncScheduledInfo : syncScheduledInfos) {
                String nowDate = DateUtils.dateStringFormat(dataSyncScheduledInfo.getTime(), HospitalVisitRecordTaskConstants.DATA_FORMAT, HospitalVisitRecordTaskConstants.DATE_FORMAT);
                beginDate = nowDate + " 00:00:00";
                endDate = nowDate + " 23:59:59";
                //2.1定义开始时间
                Date ksTime = new Date();
                String remarks = "";
                try {
                    //TODO 查询诊疗同步数据中配置的机构列表信息，去遍历同步数据
                    List<VrSynchroSettings> synchroSettingsOrgList = vrSynchroSettingsDAO.queryVrSynchroSettingsOrgListByType(type);
                    logger.info("synchroSettingsOrgList"+synchroSettingsOrgList+synchroSettingsOrgList.size());
                    for (VrSynchroSettings vrSynchroSettings : synchroSettingsOrgList) {
                        //执行查询公用方法
                        List<DiagnosisAndTreatmentDataTypeEnum> settingTypeValue = DiagnosisAndTreatmentDataTypeEnum.getSettingTypeValue(type);
                        for (DiagnosisAndTreatmentDataTypeEnum dataTypeEnum : settingTypeValue) {
                            switchSyncHisRecords(dataTypeEnum.getType(), vrSynchroSettings.getOrgId(), beginDate, endDate);
                        }
                    }
                    //任务情况 0 未完成 1 已完成 2 失败
                    dataSyncScheduledInfo.setStatus("1");
                } catch (Exception e) {
                    e.printStackTrace();
                    remarks = e.getMessage();
                    dataSyncScheduledInfo.setStatus("2");
                }
                //2.2.查询同步记录总数 执行查询公用方法
                Long todayTotal = switchSyncHisTotalRecords(type, beginDate, endDate);
                //2.3执行完成之后，更新执行任务状态
                dataSyncScheduledInfo.setBeginTime(ksTime);
                dataSyncScheduledInfo.setEndTime(new Date());
                dataSyncScheduledInfo.setTodayTotal(todayTotal);
                dataSyncScheduledInfo.setRemarks(remarks);
                dataSyncScheduledInfoDAO.update(dataSyncScheduledInfo);
            }
        }
    }

    /**
     * 动态去his获取数据，根据类型
     * 1 门诊记录 2 住院记录 3 体检记录 4 检验报告 5 检查报告 6 病理报告 7 电子病历
     * 8 医嘱记录 9 手术记录 10 治疗记录 11 用药记录 12 检验申请单 13 检查申请单
     *
     * @param type
     * @param orgId
     * @param beginDate
     * @param endDate
     */
    private void switchSyncHisRecords(Integer type, String orgId, String beginDate, String endDate) {
        switch (type) {
            case 1:
                pullOutpatientRecords(orgId, beginDate, endDate);
                break;
            case 2:
                pullInpatientVisitRecords(orgId, beginDate, endDate);
                break;
            case 3:
                pullPhysicalExaminationRecords(orgId, beginDate, endDate);
                break;
            case 4:
                pullInspectReportRecords(orgId, beginDate, endDate);
                break;
            case 5:
                pullCheckReportRecords(orgId, beginDate, endDate);
                break;
            case 6:
                pullPathologicalReportRecords(orgId, beginDate, endDate);
                break;
            case 7:
                pullElectronicMedicalRecords(orgId, beginDate, endDate);
                break;
            case 8:
                pullOrderRecords(orgId, beginDate, endDate);
                break;
            case 9:
                pullVrSurgicalRecords(orgId, beginDate, endDate);
                break;
            case 10:
                pullTreatmentInfoRecords(orgId, beginDate, endDate);
                break;
            case 11:
                pullPrescriptionRecords(orgId, beginDate, endDate);
                break;
            case 12:
                pullLabApplicationFormRecords(orgId, beginDate, endDate);
                break;
            case 13:
                pullExamApplicationFormRecords(orgId, beginDate, endDate);
                break;
            default:
                break;
        }
    }


    /**
     * 获取当天执行数据的总数
     *
     * @param type      1 门诊记录 2 住院记录 3 体检记录 4 检验报告 5 检查报告 6 病理报告 7 电子病历 8 医嘱记录 9 手术记录
     * @param beginDate
     * @param endDate
     */
    private Long switchSyncHisTotalRecords(Integer type, String beginDate, String endDate) {
        switch (type) {
            case 1:
                return vrOutpatientVisitRecordDAO.getOutpatientByToday(
                        DateUtils.dateFormate(beginDate, HospitalVisitRecordTaskConstants.DATE_FORMAT2),
                        DateUtils.dateFormate(endDate, HospitalVisitRecordTaskConstants.DATE_FORMAT2));
            case 2:
                return vrInpatientVisitRecordDAO.getInpatientVisitByToday(
                        DateUtils.dateFormate(beginDate, HospitalVisitRecordTaskConstants.DATE_FORMAT2),
                        DateUtils.dateFormate(endDate, HospitalVisitRecordTaskConstants.DATE_FORMAT2));
            case 3:
                break;
            case 4:
                return inspectReportRecordDAO.getInspectReportByToday(
                        DateUtils.dateFormate(beginDate, HospitalVisitRecordTaskConstants.DATE_FORMAT2),
                        DateUtils.dateFormate(endDate, HospitalVisitRecordTaskConstants.DATE_FORMAT2));
            case 5:
                return examReportDAO.getExamRecordByToday(
                        DateUtils.dateFormate(beginDate, HospitalVisitRecordTaskConstants.DATE_FORMAT2),
                        DateUtils.dateFormate(endDate, HospitalVisitRecordTaskConstants.DATE_FORMAT2));
            case 6:
                break;
            case 7:
                break;
            case 8:
                break;
            case 9:
                return vrSurgicalRecordDAO.getSurgicalRecordByToday(
                        DateUtils.dateFormate(beginDate, HospitalVisitRecordTaskConstants.DATE_FORMAT2),
                        DateUtils.dateFormate(endDate, HospitalVisitRecordTaskConstants.DATE_FORMAT2));
            case 10:
                return treatmentRecordDAO.getTreatmentInfoByToday(
                        DateUtils.dateFormate(beginDate, HospitalVisitRecordTaskConstants.DATE_FORMAT2),
                        DateUtils.dateFormate(endDate, HospitalVisitRecordTaskConstants.DATE_FORMAT2));
            case 11:
                return prescriptionRecordDAO.getPrescriptionByToday(
                        DateUtils.dateFormate(beginDate, HospitalVisitRecordTaskConstants.DATE_FORMAT2),
                        DateUtils.dateFormate(endDate, HospitalVisitRecordTaskConstants.DATE_FORMAT2));
            case 12:
                break;
            case 13:
                break;
            default:
                return 0L;
        }
        return 0L;
    }

    /**
     * 查询所有机构信息
     *
     * @return
     */
    private List<String> getOrganizationIdMaps() {
        List<String> orgIdList = new ArrayList<>();
        List<Map> data = new ArrayList<>();
        ParamsOrgQo request = new ParamsOrgQo();
        request.setType(type);
        //查询所有机构
        BaseResponse listBaseResponse = baseDataService.queryOrganizationList(request);
        if (CommonUtils.isNotEmpty(listBaseResponse) && listBaseResponse.getCode() == ResultCode.SUCCESS && null != listBaseResponse.getData()) {
            data = (List<Map>) listBaseResponse.getData();
        }
        for (Map mapData : data) {
            if (CommonUtils.isNotEmpty(mapData)) {
                //机构代码
                String organizationId = (String) mapData.get("organizationId");
                if (CommonUtils.isEmpty(organizationId)) {
                    continue;
                }
                orgIdList.add(organizationId);
            }
        }
        return orgIdList;
    }
/**============================================1.门诊记录同步开始===========================================**/
    /**
     * @description: 同步门诊/就诊记录
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/1/4 11:22
     * @param: hisUrl
     * @param: organizationId
     * @param: beginDate
     * @param: endDate
     * @return: void
     */
    public void pullOutpatientRecords(String organizationId, String beginDate, String endDate) {
        //xml拉取
        Calendar calendar = Calendar.getInstance();
        /* HOUR_OF_DAY 指示一天中的小时 */
        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - 24);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logger.info("开始进入json拉取数据");
        QueryRecordRequest recordRequest = new QueryRecordRequest();
        recordRequest.setOrganizationId(organizationId);
        recordRequest.setBeginDate(df.format(calendar.getTime()));
        recordRequest.setEndDate(df.format(new Date()));
//        recordRequest.setBeginDate(beginDate);
//        recordRequest.setEndDate(endDate);
        Long total;
        int pageNo = 1;
        recordRequest.setPageSize(1000);
        recordRequest.setPageNo(pageNo);
        total=   syncOutpatientRecordsJson(recordRequest);
        //total = syncOutpatientRecordsXml(recordRequest);
//        if (total > recordRequest.getPageSize()) {
//            Long size = total / recordRequest.getPageSize();
//            for (int i = 0; i < size; i++) {
//                pageNo++;
//                recordRequest.setPageNo(pageNo);
//                syncOutpatientRecordsJson(recordRequest);
//            }
//        }
    }

    /**
     * 同步门诊/就诊记录, xml同步
     *
     * @param request
     * @return
     */
    public Long syncOutpatientRecordsXml(QueryRecordRequest request) {
        logger.info("组装数据");
        String serviceName = PlatFormServiceEnum.QueryOutpatientRecord.getServiceName();
        String msgType = PlatFormServiceEnum.QueryOutpatientRecord.getServiceCode();
        //组装xml请求入参
        HisXmlRequest<QueryRecordRequest> req = new HisXmlRequest<>();
        req.setHeader(HisXmlHeader.Builder.custom()
                .organization(request.getOrganizationId())
                .sender("GOL")
                .serviceType(Constants.SERVICE_TYPE_SERVICE)
                .msgType(msgType)
                .build());
        req.setBody(request);
        try {
            logger.info("开始执行拉取数据 "+"----------"+request.getBeginDate()+request.getEndDate()+request.getOrganizationId());
            OutpatientRecordDataVo dataVo = ServiceController.instance().singleWork(serviceName, request.getOrganizationId(), req, OutpatientRecordDataVo.class);
            if (null != dataVo) {
                List<OutpatientRecordVo> records = dataVo.getD_MYD_MZ().getD_MYD_MZ_row();
                operateOutpatientRecordVoList(records);
                return dataVo.getTotal() == null ? 0L : dataVo.getTotal();
            }
        } catch (ControllerException e) {
            logger.error("定时任务同步历史门诊记录失败,失败原因=" + e.getMessage());
        }
        return 0L;
    }
     /**
      * @describe  同步门诊记录 json同步
      * @author  hdh
      * @date 2023/6/2 13:12
      * @param request
      * @return Long
      */
    public Long syncOutpatientRecordsJson(QueryRecordRequest request){
       logger.info("入参---"+request);
        JSONObject jsonParams=(JSONObject) JSONObject.toJSON(request);
        jsonParams.put("organizationId", "2003");
        jsonParams.put("funcode", "ODS_QueryOutpatientRecord");
        jsonParams.put("beginDateTime",jsonParams.remove("beginDate"));
        jsonParams.put("endDateTime",jsonParams.remove("endDate"));
        //请求接口
        logger.info("入参-----------------接口"+jsonParams);
        JSONObject json=   WebServiceUtil.openWSDL2(null, XmlToJson.getXML2(jsonParams.toString()));
        logger.info("接口返回"+json);
        try{
//            if (json.getInteger("code")==Constants.SUCCESS_CODE) {
//                 if (json.containsKey("data")&& json.get("data") !=null && json.getJSONArray("data").isEmpty()){
//                     OutpatientRecordDataVo dataVo=     JSONObject.parseObject(json.getJSONObject("data").toJSONString(),OutpatientRecordDataVo.class);
//                     if (null != dataVo) {
//                         List<OutpatientRecordVo> records = dataVo.getD_MYD_MZ().getD_MYD_MZ_row();
//                         operateOutpatientRecordVoList(records);
//                         return dataVo.getTotal() == null ? 0L : dataVo.getTotal();
//                     }
//                 }
//            }
             OutpatientRecordDataVo dataVo=     JSONObject.parseObject(json.getJSONObject("Data").toJSONString(),OutpatientRecordDataVo.class);
             if (null != dataVo) {
                List<OutpatientRecordVo> records = dataVo.getD_MYD_MZ().getD_MYD_MZ_row();
                operateOutpatientRecordVoList(records);
                return Long.valueOf(dataVo.getD_MYD_MZ().getD_MYD_MZ_row().size())== null ? 0L : dataVo.getD_MYD_MZ().getD_MYD_MZ_row().size();
            }
        }catch (Exception e){
            logger.error("定时任务同步历史门诊记录失败"+e.getMessage());
        }
        return  0L;
    }
    /**
     * @description: 保存门诊记录
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/12/12 14:25
     * @param: outpatientRecordVoList
     * @return: void
     */
    public void operateOutpatientRecordVoList(List<OutpatientRecordVo> outpatientRecordVoList) {
        if (CommonUtils.isNotEmpty(outpatientRecordVoList)) {
            for (OutpatientRecordVo outpatientRecordVo : outpatientRecordVoList) {
                try {
                    String visitNo = outpatientRecordVo.getVisitNo();
                    String voOrganizationId = outpatientRecordVo.getOrganizationId();

                    if (CommonUtils.isNotEmpty(visitNo) && CommonUtils.isNotEmpty(voOrganizationId)) {
                        //根据机构代码和就诊序号查询是否已同步就诊记录
                        VrOutpatientVisitRecord vrOutpatientVisitRecord = vrOutpatientVisitRecordDAO.getVrOutpatientVisitRecord(visitNo, voOrganizationId);
                        //已存在门诊记录，不再保存
                        if (null != vrOutpatientVisitRecord) {
                            continue;
                        }
                        vrOutpatientVisitRecord = new VrOutpatientVisitRecord();
                        BeanUtils.copy(outpatientRecordVo, vrOutpatientVisitRecord);
                        vrOutpatientVisitRecord.setStartTime(CommonUtils.isEmpty(outpatientRecordVo.getStartTime()) ? null : DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss", outpatientRecordVo.getStartTime()));
                        vrOutpatientVisitRecord.setEndTime(CommonUtils.isEmpty(outpatientRecordVo.getEndTime()) ? null : DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss", outpatientRecordVo.getEndTime()));
                        vrOutpatientVisitRecord.setPatientBirthday(CommonUtils.isEmpty(outpatientRecordVo.getPatientBirthday()) ? null : DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss", outpatientRecordVo.getPatientBirthday()));
                        String visitRecordId = UUID.randomUUID().toString();
                        vrOutpatientVisitRecord.setVisitRecordId(visitRecordId);
                        vrOutpatientVisitRecord.setSatisfactionStatus("0");
                        if (null == vrOutpatientVisitRecord.getPatientBirthday() || null == vrOutpatientVisitRecord.getPatientSex() || null == vrOutpatientVisitRecord.getPatientAge()) {
                            try {
                                //从身份证里面获取信息
                                if ("01".equals(vrOutpatientVisitRecord.getCardType()) && CommonUtils.isNotEmpty(vrOutpatientVisitRecord.getCardNumber())) {
                                    vrOutpatientVisitRecord.setPatientBirthday(IdcardUtil.getBirthDayTime(vrOutpatientVisitRecord.getCardNumber()));
                                    vrOutpatientVisitRecord.setPatientAge(Byte.valueOf(String.valueOf(IdcardUtil.getAge(vrOutpatientVisitRecord.getCardNumber()))));
                                    if (null != IdcardUtil.getSex(vrOutpatientVisitRecord.getCardNumber())) {
                                        vrOutpatientVisitRecord.setPatientSex(IdcardUtil.getSex(vrOutpatientVisitRecord.getCardNumber()).toString());
                                    }
                                    if (CommonUtils.isNotEmpty(vrOutpatientVisitRecord.getPatientAgeText())) {
                                        vrOutpatientVisitRecord.setPatientAgeText(vrOutpatientVisitRecord.getPatientAge() + "岁");
                                    }
                                }
                            } catch (Exception e) {
                                logger.error("从证件获取出生日期等信息失败");
                            }
                        }
                        vrOutpatientVisitRecord.setCreateTime(new Date());
                        VrOutpatientVisitRecord saveVrOutpatientVisitRecord = vrOutpatientVisitRecordDAO.save(vrOutpatientVisitRecord);

                        List<VrVisitDiagnosisVo> diagnosisList = outpatientRecordVo.getDiagnosisList();

                        if (CommonUtils.isNotEmpty(diagnosisList)) {
                            for (VrVisitDiagnosisVo vrVisitDiagnosisVo : diagnosisList) {
                                VrVisitDiagnosis visitDiagnosis = new VrVisitDiagnosis();
                                BeanUtils.copy(vrVisitDiagnosisVo, visitDiagnosis);
                                String diagnosticRecordId = UUID.randomUUID().toString();
                                visitDiagnosis.setDiagnosticRecordId(diagnosticRecordId);
                                visitDiagnosis.setBusinessId(vrOutpatientVisitRecord.getVisitRecordId());
                                visitDiagnosis.setBusinessType("1");
                                //诊断业务类型，1入院诊断、2出院诊断、3门诊诊断、5其他诊断
                                visitDiagnosis.setDiagnosisServiceType("3");//门诊直接设置诊断类型
                                if ("1".equals(vrVisitDiagnosisVo.getMainDiagnosisMark())) {
                                    vrOutpatientVisitRecord.setMainDiagnosisCode(vrVisitDiagnosisVo.getDiseasesCode());
                                    vrOutpatientVisitRecord.setMainDiagnosisName(vrVisitDiagnosisVo.getDiseasesName());
                                }
                                //保存患者patientId
                                visitDiagnosis.setPatientId(vrOutpatientVisitRecord.getPatientId());
                                vrVisitDiagnosisDAO.save(visitDiagnosis);
                            }
                            vrOutpatientVisitRecordDAO.update(vrOutpatientVisitRecord);
                        }
                        //更新businessId
                        updateBusinessId("1", vrOutpatientVisitRecord.getVisitNo(), saveVrOutpatientVisitRecord);
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage());
                }
            }
        }
    }
/**============================================门诊记录同步结束===========================================**/

/**============================================2.住院记录同步开始===========================================**/
    /**
     * @description: 同步住院记录
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/1/4 11:22
     * @param: hisUrl
     * @param: organizationId
     * @param: beginDate
     * @param: endDate
     * @return: void
     */
    public void pullInpatientVisitRecords(String organizationId, String beginDate, String endDate) {
        //json拉取
      //syncInpatientVisitRecord(hisUrl, organizationId, beginDate, endDate);
        //xml拉取
        //xml拉取
        Calendar calendar = Calendar.getInstance();
        /* HOUR_OF_DAY 指示一天中的小时 */
        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - 24);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logger.info("开始进入json拉取数据");
        QueryRecordRequest recordRequest = new QueryRecordRequest();
        recordRequest.setOrganizationId(organizationId);
        recordRequest.setBeginDate(df.format(calendar.getTime()));
        recordRequest.setEndDate(df.format(new Date()));
        int pageNo = 1;
        recordRequest.setPageSize(10000);
        recordRequest.setPageNo(pageNo);
        logger.info("执行住院的操作");
        syncInpatientVisitRecordJson(recordRequest);
//        syncInpatientVisitRecordXml(recordRequest);
//        Long total = syncInpatientVisitRecordXml(recordRequest);
//        if (total > recordRequest.getPageSize()) {
//            Long size = total / recordRequest.getPageSize();
//            for (int i = 0; i < size; i++) {
//                pageNo++;
//                recordRequest.setPageNo(pageNo);
//                syncInpatientVisitRecordXml(recordRequest);
//            }
//        }
    }

    /**
     * 同步住院记录xml格式
     *
     * @param request
     * @return
     */

    public Long syncInpatientVisitRecordXml(QueryRecordRequest request) {
        String serviceName = PlatFormServiceEnum.QueryInpatientRecord.getServiceName();
        String msgType = PlatFormServiceEnum.QueryInpatientRecord.getServiceCode();
        //组装xml请求入参
        request.setAutherOrganization(request.getOrganizationId());
        HisXmlRequest<QueryRecordRequest> req = new HisXmlRequest<>();
        req.setHeader(HisXmlHeader.Builder.custom()
                .organization(request.getOrganizationId())
                .sender("GOL")
                .serviceType(Constants.SERVICE_TYPE_SERVICE)
                .msgType(msgType)
                .build());
        req.setBody(request);
        try {
            InpatientVisitRecordDataVo dataVo = ServiceController.instance().singleWork(serviceName, request.getOrganizationId(), req, InpatientVisitRecordDataVo.class);
            if (null != dataVo) {
                List<InpatientVisitRecordVo> records = dataVo.getRecords().getRecord();
                operateInpatientVisitRecord(records);
                return dataVo.getTotal();
            }
        } catch (ControllerException e) {
            logger.error("定时任务同步历史住院记录失败,失败原因=" + e.getMessage());
        }
        return 0L;
    }
    /**
     * @describe 同步住院记录 进行json形式进行交互
     * @author  hdh
     * @date 2023/6/2 15:43
     * @param request
     * @return Long
     */

    public Long syncInpatientVisitRecordJson(QueryRecordRequest request){
        logger.info("入参"+request);
        //入参转换
        JSONObject jsonParams=(JSONObject) JSONObject.toJSON(request);
        jsonParams.put("organizationId", "2003");
        jsonParams.put("funcode", "ODS_QueryInpatientRecord");
        jsonParams.put("beginDateTime",jsonParams.remove("beginDate"));
        jsonParams.put("endDateTime",jsonParams.remove("endDate"));
        //接口调用
        JSONObject json = WebServiceUtil.openWSDL2(null, XmlToJson.getXML2(jsonParams.toString()));
        logger.info("接口返回"+json);
        try{
            if (json.getInteger("Code")==Constants.SUCCESS_CODE) {
                if (json.containsKey("Data")&& json.get("Data") !=null && !json.getJSONObject("Data").isEmpty()){
                    InpatientVisitRecordDataVo dataVo=     JSONObject.parseObject(json.getJSONObject("Data").toJSONString(),InpatientVisitRecordDataVo.class);
                    if (null != dataVo) {
                        List<InpatientVisitRecordVo> records = dataVo.getRecords().getRecord();
                        logger.info("开始保存住院");
                        operateInpatientVisitRecord(records);
                        return Long.valueOf(dataVo.getRecords().getRecord().size())==null ? 0L :dataVo.getRecords().getRecord().size();
                    }
                }
            }
        }catch (Exception e){
            logger.error("定时任务同步历史住院记录失败"+e.getMessage());
        }
        return 0L;
    }
    /**
     * @description: 保存住院记录
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/12/12 14:25
     * @param: outpatientRecordVoList
     * @return: void
     */
    public void operateInpatientVisitRecord(List<InpatientVisitRecordVo> inpatientVisitRecordVos) {
        logger.info("进入住院方法。。。。。。。。。。。。。。");
        if (CommonUtils.isNotEmpty(inpatientVisitRecordVos)) {
            for (InpatientVisitRecordVo inpatientVisitRecordVo : inpatientVisitRecordVos) {
                try {
                    String visitNo = inpatientVisitRecordVo.getVisitNo();
                    String organizationId = inpatientVisitRecordVo.getOrganizationId();

                    if (CommonUtils.isNotEmpty(visitNo) && CommonUtils.isNotEmpty(organizationId)) {
                        //根据机构代码和住院号查询是否已同步就诊记录
                        VrInpatientVisitRecord vrInpatientVisitRecord = vrInpatientVisitRecordDAO.getVrInpatientVisitRecord(visitNo, organizationId);
                        // TODO  已存在住院记录，更新该条记录 3.5.01修改
                        if (null != vrInpatientVisitRecord) {//更新
                            BeanUtils.copy(inpatientVisitRecordVo, vrInpatientVisitRecord);
                            //更新诊断信息
                            List<VrVisitDiagnosisVo> diagnosisList = inpatientVisitRecordVo.getDiagnosisList();
                            if (CommonUtils.isNotEmpty(diagnosisList)) {
                                //先删除，再保存诊断
                                List<VrVisitDiagnosis> vrVisitDiagnoses = vrVisitDiagnosisDAO.queryVrVisitDiagnosis(vrInpatientVisitRecord.getHospitalRecordId());
                                for (VrVisitDiagnosis vrVisitDiagnosis : vrVisitDiagnoses) {
                                    vrVisitDiagnosisDAO.remove(vrVisitDiagnosis);
                                }
                                for (VrVisitDiagnosisVo vrVisitDiagnosisVo : diagnosisList) {
                                    VrVisitDiagnosis vrVisitDiagnosis = new VrVisitDiagnosis();
                                    BeanUtils.copy(vrVisitDiagnosisVo, vrVisitDiagnosis);
                                    vrVisitDiagnosis.setDiagnosticRecordId(UUID.randomUUID().toString());
                                    vrVisitDiagnosis.setBusinessId(vrInpatientVisitRecord.getHospitalRecordId());
                                    vrVisitDiagnosis.setBusinessType("2");
                                    //诊断业务类型，1入院诊断、2出院诊断、3门诊诊断、5其他诊断
                                    if ("1".equals(vrVisitDiagnosis.getDiagnosisServiceType())) {
                                        vrInpatientVisitRecord.setAdmissionDiagnosis(vrVisitDiagnosis.getDiseasesName());
                                    } else if ("2".equals(vrVisitDiagnosis.getDiagnosisServiceType())) {
                                        vrInpatientVisitRecord.setDischargeDiagnosis(vrVisitDiagnosis.getDiseasesName());
                                    }
                                    //保存患者patientId
                                    vrVisitDiagnosis.setPatientId(vrInpatientVisitRecord.getPatientId());
                                    vrVisitDiagnosisDAO.save(vrVisitDiagnosis);
                                }
                            }
                            vrInpatientVisitRecord.setModifyTime(new Date());
                            vrInpatientVisitRecordDAO.update(vrInpatientVisitRecord);
                        } else {//保存
                            vrInpatientVisitRecord = new VrInpatientVisitRecord();
                            BeanUtils.copy(inpatientVisitRecordVo, vrInpatientVisitRecord);
                            //目前互联互通AttendingDoctorId和AttendingDoctorName两个字段返回的是病区代码和病区名称
                            vrInpatientVisitRecord.setWardCode(inpatientVisitRecordVo.getAttendingDoctorId());
                            vrInpatientVisitRecord.setWardName(inpatientVisitRecordVo.getAttendingDoctorName());
                            vrInpatientVisitRecord.setDoctorId(inpatientVisitRecordVo.getChiefDoctorId());
                            vrInpatientVisitRecord.setAdmissionTime(CommonUtils.isEmpty(inpatientVisitRecordVo.getAdmissionTime()) ? null : DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss", inpatientVisitRecordVo.getAdmissionTime()));
                            vrInpatientVisitRecord.setDischargeTime(CommonUtils.isEmpty(inpatientVisitRecordVo.getDischargeTime()) ? null : DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss", inpatientVisitRecordVo.getDischargeTime()));
                            vrInpatientVisitRecord.setPatientBirthday(CommonUtils.isEmpty(inpatientVisitRecordVo.getPatientBirthday()) ? null : DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss", inpatientVisitRecordVo.getPatientBirthday()));
                            String hospitalRecordId = UUID.randomUUID().toString();
                            vrInpatientVisitRecord.setHospitalRecordId(hospitalRecordId);
                            vrInpatientVisitRecord.setSatisfactionStatus("0");
                            //修改赋值
                            vrInpatientVisitRecord.setAttendingDoctorId(inpatientVisitRecordVo.getDepartmentId());
                            if (null == vrInpatientVisitRecord.getPatientBirthday() || null == vrInpatientVisitRecord.getPatientSex() || null == vrInpatientVisitRecord.getPatientAge()) {
                                try {
                                    //从身份证里面获取信息
                                    if ("01".equals(vrInpatientVisitRecord.getCardType()) && CommonUtils.isNotEmpty(vrInpatientVisitRecord.getCardNumber())) {
                                        vrInpatientVisitRecord.setPatientBirthday(IdcardUtil.getBirthDayTime(vrInpatientVisitRecord.getCardNumber()));
                                        vrInpatientVisitRecord.setPatientAge(Byte.valueOf(String.valueOf(IdcardUtil.getAge(vrInpatientVisitRecord.getCardNumber()))));
                                        if (null != IdcardUtil.getSex(vrInpatientVisitRecord.getCardNumber())) {
                                            vrInpatientVisitRecord.setPatientSex(IdcardUtil.getSex(vrInpatientVisitRecord.getCardNumber()).toString());
                                        }
                                        if (CommonUtils.isNotEmpty(vrInpatientVisitRecord.getPatientAgeText())) {
                                            vrInpatientVisitRecord.setPatientAgeText(vrInpatientVisitRecord.getPatientAge() + "岁");
                                        }
                                    }
                                } catch (Exception e) {
                                    logger.error("从证件获取出生日期等信息失败");
                                }
                            }
                            vrInpatientVisitRecord.setCreateTime(new Date());
                            vrInpatientVisitRecordDAO.save(vrInpatientVisitRecord);
                            List<VrVisitDiagnosisVo> diagnosisList = inpatientVisitRecordVo.getDiagnosisList();
                            if (CommonUtils.isNotEmpty(diagnosisList)) {
                                for (VrVisitDiagnosisVo vrVisitDiagnosisVo : diagnosisList) {
                                    VrVisitDiagnosis vrVisitDiagnosis = new VrVisitDiagnosis();
                                    BeanUtils.copy(vrVisitDiagnosisVo, vrVisitDiagnosis);
                                    vrVisitDiagnosis.setDiagnosticRecordId(UUID.randomUUID().toString());
                                    vrVisitDiagnosis.setBusinessId(vrInpatientVisitRecord.getHospitalRecordId());
                                    vrVisitDiagnosis.setBusinessType("2");
                                    //诊断业务类型，1入院诊断、2出院诊断、3门诊诊断、5其他诊断
                                    if ("1".equals(vrVisitDiagnosis.getDiagnosisServiceType())) {
                                        vrInpatientVisitRecord.setAdmissionDiagnosis(vrVisitDiagnosis.getDiseasesName());
                                    } else if ("2".equals(vrVisitDiagnosis.getDiagnosisServiceType())) {
                                        vrInpatientVisitRecord.setDischargeDiagnosis(vrVisitDiagnosis.getDiseasesName());
                                    }
                                    //保存患者patientId
                                    vrVisitDiagnosis.setPatientId(vrInpatientVisitRecord.getPatientId());
                                    vrVisitDiagnosisDAO.save(vrVisitDiagnosis);
                                }
                                vrInpatientVisitRecord.setModifyTime(new Date());
                                vrInpatientVisitRecordDAO.update(vrInpatientVisitRecord);
                            }
                        }
                        //更新businessId
                        updateBusinessIdByHospital("2", vrInpatientVisitRecord.getVisitNo(), vrInpatientVisitRecord);
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage());
                }
            }
        }
    }
/**============================================住院记录同步结束===========================================**/
/**============================================3.体检记录同步开始===========================================**/
    /**
     * 同步体检记录
     *
     * @param orgId
     * @param beginDate
     * @param endDate
     */
    private void pullPhysicalExaminationRecords(String orgId, String beginDate, String endDate) {
    }
/**============================================体检记录同步结束===========================================**/

/**============================================4.检验报告同步开始===========================================**/

    /**
     * 同步检验报告
     *
     * @param organizationId
     * @param beginDate
     * @param endDate
     */

    public void pullInspectReportRecords(String organizationId, String beginDate, String endDate) {
        QueryInspectReportRequest recordRequest = new QueryInspectReportRequest();
        QueryInspectReportRequest.InnerRequest innerRequest = new QueryInspectReportRequest.InnerRequest();
        innerRequest.setOrganizationId(organizationId);
        innerRequest.setBeginDate(beginDate);
        innerRequest.setEndDate(endDate);
        int pageNo = 1;
        innerRequest.setPageSize(2000);
        innerRequest.setPageNo(pageNo);
        recordRequest.setData(innerRequest);
        Long total = syncInspectReportRecordXml(recordRequest);
        if (total > innerRequest.getPageSize()) {
            Long size = total / innerRequest.getPageSize();
            for (int i = 0; i < size; i++) {
                pageNo++;
                innerRequest.setPageNo(pageNo);
                syncInspectReportRecordXml(recordRequest);
            }
        }
    }

    /**
     * 同步检验报告信息
     *
     * @param request
     * @return
     */

    public Long syncInspectReportRecordXml(QueryInspectReportRequest request) {
        String serviceName = PlatFormServiceEnum.QueryInspectReportRecord.getServiceName();
        String msgType = PlatFormServiceEnum.QueryInspectReportRecord.getServiceCode();
        //组装xml请求入参
        HisXmlRequest<QueryInspectReportRequest> req = new HisXmlRequest<>();
        req.setHeader(HisXmlHeader.Builder.custom()
                .organization(request.getData().getOrganizationId())
                .sender("GOL")
                .serviceType(Constants.SERVICE_TYPE_SERVICE)
                .msgType(msgType)
                .build());
        req.setBody(request);
        try {
            InspectReportRecordDataVo dataVo = ServiceController.instance().singleWork(serviceName, request.getData().getOrganizationId(), req, InspectReportRecordDataVo.class);
            if (null != dataVo) {
                List<InspectReportRecordVo> records = dataVo.getRecords();
                operateInspectReportRecord(records);
                return dataVo.getTotal();
            }
        } catch (ControllerException e) {
            logger.error("定时任务同步检验报告记录失败=" + e.getMessage());
        }
        return 0L;
    }

    /**
     * 保存检验报告信息
     *
     * @param records
     */
    public void operateInspectReportRecord(List<InspectReportRecordVo> records) {
        if (CommonUtils.isNotEmpty(records)) {
            for (InspectReportRecordVo inspectReportRecordVo : records) {
                try {
                    //检验报告单编号
                    String reportId = inspectReportRecordVo.getReportId();
                    //机构id
                    String visitOrganization = inspectReportRecordVo.getVisitOrganization();
                    if (CommonUtils.isNotEmpty(reportId) && CommonUtils.isNotEmpty(visitOrganization)) {
                        //根据检验报告单id和机构id查询是否已同步检验报告记录
                        InspectReportRecordEntity inspectReportRecord = inspectReportRecordDAO.getInspectReportRecordByReportId(reportId, visitOrganization);
                        if (CommonUtils.isNotEmpty(inspectReportRecord)) {
                            //已存在检验报告记录，不再保存
                            continue;
                        }
                        inspectReportRecord = new InspectReportRecordEntity();
                        BeanUtils.copy(inspectReportRecordVo, inspectReportRecord);
                        String inspectReportRecordId = UUID.randomUUID().toString();
                        inspectReportRecord.setInspectReportRecordId(inspectReportRecordId);
                        inspectReportRecord.setBusinessType(CommonUtils.isEmpty(inspectReportRecordVo.getPatientType()) ? null : inspectReportRecordVo.getPatientType());
                        inspectReportRecord.setReportTime(CommonUtils.isEmpty(inspectReportRecordVo.getReportTime()) ? null : DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss", inspectReportRecordVo.getReportTime()));
                        inspectReportRecord.setReportCheckTime(CommonUtils.isEmpty(inspectReportRecordVo.getReportCheckTime()) ? null : DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss", inspectReportRecordVo.getReportCheckTime()));
                        inspectReportRecord.setSampleTestTime(CommonUtils.isEmpty(inspectReportRecordVo.getSampleTestTime()) ? null : DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss", inspectReportRecordVo.getSampleTestTime()));
                        inspectReportRecord.setCreateTime(new Date());
                        inspectReportRecordDAO.save(inspectReportRecord);
                        //保存详情结果
                        List<InspectReportRoutineDetailEntity> inspectReportRoutineDetails = inspectReportRecordVo.getResultDetails();
                        if (CommonUtils.isNotEmpty(inspectReportRoutineDetails)) {
                            for (InspectReportRoutineDetailEntity routineDetailEntity : inspectReportRoutineDetails) {
                                String inspectReportRoutineDetailId = UUID.randomUUID().toString();
                                routineDetailEntity.setInspectReportRoutineDetailId(inspectReportRoutineDetailId);
                                routineDetailEntity.setInspectReportId(inspectReportRecord.getInspectReportRecordId());
                                routineDetailEntity.setCreateTime(new Date());
                                inspectReportRoutineDetailDAO.save(routineDetailEntity);
                            }
                        }
                        //保存培养结果
                        List<InspectReportMicrobeResultEntity> inspectReportMicrobeResult = inspectReportRecordVo.getPlantResult();
                        if (CommonUtils.isNotEmpty(inspectReportMicrobeResult)) {
                            for (InspectReportMicrobeResultEntity inspectReport : inspectReportMicrobeResult) {
                                String inspectReportMicrobeResultId = UUID.randomUUID().toString();
                                inspectReport.setInspectReportMicrobeResultId(inspectReportMicrobeResultId);
                                inspectReport.setInspectReportId(inspectReportRecord.getInspectReportRecordId());
                                inspectReport.setCreateTime(new Date());
                                inspectReportMicrobeResultDAO.save(inspectReport);
                            }
                        }
                        //保存细菌结果
                        List<InspectReportMicrobeRecordEntity> inspectReportMicrobeRecord = inspectReportRecordVo.getBioResults();
                        if (CommonUtils.isNotEmpty(inspectReportMicrobeRecord)) {
                            for (InspectReportMicrobeRecordEntity inspectReportMicrobe : inspectReportMicrobeRecord) {
                                String inspectReportMicrobeRecordId = UUID.randomUUID().toString();
                                inspectReportMicrobe.setInspectReportMicrobeRecordId(inspectReportMicrobeRecordId);
                                inspectReportMicrobe.setInspectReportId(inspectReportRecord.getInspectReportRecordId());
                                inspectReportMicrobe.setCreateTime(new Date());
                                inspectReportMicrobeRecordDAO.save(inspectReportMicrobe);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage());
                }
            }
        }
    }
/**============================================检验报告同步结束===========================================**/


/**============================================5.检查报告同步开始===========================================**/
    /**
     * @Describe: 同步检查报告
     * @Param: [hisUrl, organizationId, beginDate, endDate]
     * @Return: void
     * @Author: zhengcb10708
     * @Date: 2021/11/1 15:42
     */

    public void pullCheckReportRecords(String organizationId, String beginDate, String endDate) {
        //xml拉取
        HospitalExamReportListRequest request = new HospitalExamReportListRequest();
        request.setOrganizationId(organizationId);
        request.setBeginTime(beginDate);
        request.setEndTime(endDate);
        Long total;
        int pageNo = 1;
        request.setPageSize(2000);
        request.setPageNo(pageNo);
        total = synCheckReportXML(request);
        if (total > request.getPageSize()) {
            Long size = total / request.getPageSize();
            for (int i = 0; i < size; i++) {
                pageNo++;
                request.setPageNo(pageNo);
                synCheckReportXML(request);
            }
        }
    }

    /**
     * @param request
     * @return
     * @description: 同步检查报告, xml同步
     */
    public Long synCheckReportXML(HospitalExamReportListRequest request) {
        logger.info("获取检查报告列表请求入参=" + JSONUtils.writeValueAsString(request));
        String serviceName = PlatFormServiceEnum.ExamReportQueryList.getServiceName();
        String msgType = PlatFormServiceEnum.ExamReportQueryList.getServiceCode();
        HisXmlRequest<HospitalExamReportListRequest> req = new HisXmlRequest<>();
        req.setHeader(HisXmlHeader.Builder.custom()
                .organization(request.getOrganizationId())
                .sender("GOL")
                .serviceType(Constants.SERVICE_TYPE_SERVICE)
                .msgType(msgType)
                .build());
        req.setBody(request);
        try {
            HospitalExamReportListResponse hospitalExamReportListResponse = ServiceController.instance().singleWork(serviceName, request.getOrganizationId(), req, HospitalExamReportListResponse.class);
            if (hospitalExamReportListResponse != null) {
                saveCheckReportListData(hospitalExamReportListResponse);
                return hospitalExamReportListResponse.getTotal();
            }
        } catch (ControllerException e) {
            logger.error("定时任务同步检查报告失败，失败原因:" + e.getMessage());
        }
        return 0L;
    }

    /**
     * @Describe: 保存报告查询数据
     * @Param: [hospitalExamReportListResponse]
     * @Return: void
     * @Author: zhengcb10708
     * @Date: 2021/11/1 18:44
     */
    public void saveCheckReportListData(HospitalExamReportListResponse examList) {
        if (examList != null && CommonUtils.isNotEmpty(examList.getList())) {
            try {
                for (HospitalExamReportListResponse.HospitalExamReport examReport : examList.getList()) {
                    String voReportId = examReport.getReportId();
                    String voOrganizationId = examReport.getReportOrganization();

                    if (CommonUtils.isNotEmpty(voReportId) && CommonUtils.isNotEmpty(voOrganizationId)) {
                        //根据检查报告id和报告机构code判断是否已经同步
                        ExamReportEntity examReportEntity = examReportDAO.getExamReportByReportId(voReportId, voOrganizationId);
                        //已存在检查报告记录，不再保存
                        if (examReportEntity != null) {
                            continue;
                        }
                        examReportEntity = new ExamReportEntity();
                        Timestamp nowTime = new Timestamp(System.currentTimeMillis());
                        BeanUtils.copy(examReport, examReportEntity);
                        examReportEntity.setExamReportId(UUID.randomUUID().toString());
                        //1.门诊 2.住院 3.体检 4.急诊 5绿色通道
                        examReportEntity.setBusinessType(CommonUtils.isEmpty(examReport.getPatientType()) ? null : examReport.getPatientType());
                        examReportEntity.setAge(examReport.getAge());
                        examReportEntity.setExecuteDatetime(CommonUtils.isEmpty(examReport.getExecuteDate()) ? null : Timestamp.valueOf(examReport.getExecuteDate()));
                        examReportEntity.setReportDatetime(CommonUtils.isEmpty(examReport.getReportDate()) ? null : Timestamp.valueOf(examReport.getReportDate()));
                        examReportEntity.setReviewDatetime(CommonUtils.isEmpty(examReport.getReviewDate()) ? null : Timestamp.valueOf(examReport.getReviewDate()));
                        examReportEntity.setExamItemCode(examReport.getExamItemCode());
                        examReportEntity.setCreateTime(nowTime);
                        examReportEntity.setModifyTime(nowTime);
                        examReportDAO.save(examReportEntity);
                        //检查报告字表——图像信息表数据保存
                        if (CommonUtils.isNotEmpty(examReport.getExamList())) {
                            for (HospitalExamReportListResponse.HospitalExamReport.ExamImage examImage : examReport.getExamList()) {
                                ExamReportImage examReportImage = new ExamReportImage();
                                BeanUtils.copy(examImage, examReportImage);
                                examReportImage.setExamReportId(examReportEntity.getExamReportId());
                                examReportImageDAO.save(examReportImage);
                            }
                        }
                    }
                }
            } catch (DAOException e) {
                logger.error("同步检查报告数据保存失败，失败原因:" + e.getMessage());
            }
        }
    }

/**============================================检查报告同步结束===========================================**/
/**============================================6.病理报告同步开始===========================================**/
    /**
     * 定时同步病理报告
     *
     * @param orgId
     * @param beginDate
     * @param endDate
     */
    private void pullPathologicalReportRecords(String orgId, String beginDate, String endDate) {
    }

/**============================================病理报告同步结束===========================================**/
/**============================================7.电子病历同步开始===========================================**/
    /**
     * 定时同步电子病历
     *
     * @param orgId
     * @param beginDate
     * @param endDate
     */
    private void pullElectronicMedicalRecords(String orgId, String beginDate, String endDate) {
    }

/**============================================电子病历同步结束===========================================**/
/**============================================8.医嘱记录同步开始===========================================**/

    /**
     * 定时同步医嘱记录
     *
     * @param orgId
     * @param beginDate
     * @param endDate
     */
    private void pullOrderRecords(String orgId, String beginDate, String endDate) {
    }

/**============================================医嘱记录同步结束===========================================**/
/**============================================9.手术记录同步开始===========================================**/
    /**
     * @description: 同步手术记录
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/1/4 11:22
     * @param: hisUrl
     * @param: organizationId
     * @param: beginDate
     * @param: endDate
     * @return: void
     */
    public void pullVrSurgicalRecords(String organizationId, String beginDate, String endDate) {
        //json拉取
//        syncVrSurgicalRecord(hisUrl, organizationId, beginDate, endDate);
        //xml拉取
        QueryRecordRequest recordRequest = new QueryRecordRequest();
        recordRequest.setOrganizationId(organizationId);
        recordRequest.setBeginDate(beginDate);
        recordRequest.setEndDate(endDate);
        Long total;
        int pageNo = 1;
        recordRequest.setPageSize(2000);
        int i = 0;
        while (true) {
            recordRequest.setPageNo(pageNo);
            total = syncVrSurgicalRecordXml(recordRequest);
            if (total == 0) {
                break;
            }
            i++;
            if (i > 1000) {
                //最多查询1000次  就跳出循环，不然死循环
                break;
            }
            pageNo++;
            recordRequest.setPageNo(pageNo);
        }
    }

    /**
     * @Description: 同步手术记录-xml
     * @Author: zhaorb
     * @Date: 2020/12/11 14:52
     **/

    public Long syncVrSurgicalRecordXml(QueryRecordRequest request) {
        logger.info("syncVrSurgicalRecordXml入参：{}", JSONObject.toJSONString(request));
        BaseResponse baseResponse = new BaseResponse<>();
        //平台服务名称
        String serviceName = PlatFormServiceEnum.QUERY_OPERATION_RECORD.getServiceName();
        //参数中msgType
        String msgType = PlatFormServiceEnum.QUERY_OPERATION_RECORD.getServiceCode();
        HisXmlRequest<QueryRecordRequest> req = new HisXmlRequest<>();
        req.setHeader(HisXmlHeader.Builder.custom()
                .organization(request.getOrganizationId())
                .sender("GOL")
                .serviceType(Constants.SERVICE_TYPE_SERVICE)
                .msgType(msgType)
                .build());
        req.setBody(request);
        try {
            VrSurgicalRecordResponseList dataVo = ServiceController.instance().singleWork(serviceName, request.getOrganizationId(), req, VrSurgicalRecordResponseList.class);
            if (dataVo != null) {
                List<VrSurgicalRecordResponse> records = dataVo.getRecord();
                if (CommonUtils.isNotEmpty(records)) {
                    for (VrSurgicalRecordResponse recordResponse : records) {
                        try {
                            String operationNumber = recordResponse.getOperationSourceId();
                            String voOrganizationId = recordResponse.getVisitOrganization();

                            if (CommonUtils.isNotEmpty(operationNumber) && CommonUtils.isNotEmpty(voOrganizationId)) {
                                //根据机构代码和手术单查询是否已同步就诊记录
                                VrSurgicalRecord surgicalRecord = vrSurgicalRecordDAO.getVrSurgicalRecord(operationNumber, voOrganizationId);
                                //已存在手术记录，不再保存
                                if (null != surgicalRecord) {
                                    continue;
                                }
                                operationVrSurgicalRecord(recordResponse);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            logger.error(e.getMessage());
                        }
                    }
                }
                return dataVo.getTotal();
            }
        } catch (ControllerException e) {
            logger.error("定时任务同步手术记录失败，失败原因:" + e.getMessage());
        }
        return 0L;
    }

    /**
     * 处理手术记录信息
     *
     * @param recordResponse
     */
    private void operationVrSurgicalRecord(VrSurgicalRecordResponse recordResponse) {
        VrSurgicalRecord surgicalRecord;
        surgicalRecord = new VrSurgicalRecord();
        //字段装换
        surgicalRecord.setOrganizationId(recordResponse.getVisitOrganization());
        surgicalRecord.setOrganizationName(recordResponse.getVisitOrganizationName());
//                                surgicalRecord.setOrganizationId(recordResponse.getOperationType());
        surgicalRecord.setPatientId(recordResponse.getSourcePatientId());
        surgicalRecord.setPatientName(recordResponse.getName());
        surgicalRecord.setInHospitalRecordCode(recordResponse.getVisitId());
        surgicalRecord.setPatientSex(recordResponse.getSex());
        surgicalRecord.setTelephone(recordResponse.getContactNo());
        //1门诊手术 3日间手术 2住院手术 取值为1和3时，认定为门诊类型的手术记录
        surgicalRecord.setBusinessType("2".equals(recordResponse.getOperationType()) == true ? "2" : "1");
        surgicalRecord.setVisitId(recordResponse.getVisitId());
        surgicalRecord.setPatientBirthday(CommonUtils.isEmpty(recordResponse.getBirthDate()) ? null : DateUtil.getDateTime(
                "yyyy-MM-dd HH:mm:ss", recordResponse.getBirthDate()));
        surgicalRecord.setPatientAge(Byte.valueOf(recordResponse.getAge()));
        surgicalRecord.setPatientAgeText(recordResponse.getAge());
        surgicalRecord.setCardType(recordResponse.getIdCardCode());
        surgicalRecord.setCardNumber(recordResponse.getIdCard());
        surgicalRecord.setPatientMedicalCardType(recordResponse.getMedicalCardType());
        surgicalRecord.setPatientMedicalCardNumber(recordResponse.getMedicalCardId());
        surgicalRecord.setOperationNumber(recordResponse.getOperationSourceId());
        surgicalRecord.setOperationCode(recordResponse.getOperationCode());
        surgicalRecord.setOperationName(recordResponse.getOperationName());
        surgicalRecord.setOperationLevel(recordResponse.getOperationLevel());
        surgicalRecord.setStartTime(CommonUtils.isEmpty(recordResponse.getOperationBeginTime()) ? null : DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss", recordResponse.getOperationBeginTime()));
        surgicalRecord.setEndTime(CommonUtils.isEmpty(recordResponse.getOperationEndTime()) ? null : DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss", recordResponse.getOperationEndTime()));
        surgicalRecord.setDepartmentId(recordResponse.getDeptCode());
        surgicalRecord.setDepartmentName(recordResponse.getDeptName());
        surgicalRecord.setAnesthesiaWayCode(recordResponse.getAnesthesiaWayCode());
        surgicalRecord.setAnesthesiaWayName(recordResponse.getAnesthesiaWayCode());
        surgicalRecord.setPreoperativeDiagnosisCode(recordResponse.getPreoperativeDiagnosisCode());
        surgicalRecord.setPreoperativeDiagnosis(recordResponse.getPreoperativeDiagnosis());
        surgicalRecord.setPostoperativeDiagnosisCode(recordResponse.getPostoperativeDiagnosisCode());
        surgicalRecord.setPostoperativeDiagnosis(recordResponse.getPostoperativeDiagnosis());
        surgicalRecord.setOperationIncisionDescription(recordResponse.getOperationIncisionDescription());
        surgicalRecord.setOperationIncisionHealLevel(recordResponse.getOperationIncisionHealLevel());
        surgicalRecord.setSatisfactionStatus("0");

        String operationRecordId = UUID.randomUUID().toString();
        surgicalRecord.setOperationRecordId(operationRecordId);
        surgicalRecord.setCreateTime(new Date());
        vrSurgicalRecordDAO.save(surgicalRecord);
    }
/**============================================手术记录同步结束===========================================**/


/**============================================治疗信息同步开始===========================================**/
    /**
     * 同步治疗信息
     *
     * @param organizationId
     * @param beginDate
     * @param endDate
     */
    public void pullTreatmentInfoRecords(String organizationId, String beginDate, String endDate) {
        QueryRecordRequest recordRequest = new QueryRecordRequest();
        recordRequest.setOrganizationId(organizationId);
        recordRequest.setBeginDate(beginDate);
        recordRequest.setEndDate(endDate);
        int pageNo = 1;
        recordRequest.setPageSize(2000);
        recordRequest.setPageNo(pageNo);
        Long total = syncTreatmentInfoRecordXml(recordRequest);
        if (total > recordRequest.getPageSize()) {
            Long size = total / recordRequest.getPageSize();
            for (int i = 0; i < size; i++) {
                pageNo++;
                recordRequest.setPageNo(pageNo);
                syncTreatmentInfoRecordXml(recordRequest);
            }
        }
    }

    /**
     * 同步治疗信息
     *
     * @param request
     * @return
     */

    public Long syncTreatmentInfoRecordXml(QueryRecordRequest request) {
        String serviceName = PlatFormServiceEnum.QueryTreatmentInfoRecord.getServiceName();
        String msgType = PlatFormServiceEnum.QueryTreatmentInfoRecord.getServiceCode();
        //组装xml请求入参
        HisXmlRequest<QueryRecordRequest> req = new HisXmlRequest<>();
        req.setHeader(HisXmlHeader.Builder.custom()
                .organization(request.getOrganizationId())
                .sender("GOL")
                .serviceType(Constants.SERVICE_TYPE_SERVICE)
                .msgType(msgType)
                .build());
        req.setBody(request);
        try {
            TreatmentInfoRecordDataVo dataVo = ServiceController.instance().singleWork(serviceName, request.getOrganizationId(), req, TreatmentInfoRecordDataVo.class);
            if (null != dataVo) {
                List<TreatmentInfoVo> records = dataVo.getRecords();
                operateTreatmentInfoRecord(records);
                return dataVo.getTotal();
            }
        } catch (ControllerException e) {
            logger.error("定时任务同步治疗记录失败,失败原因:" + e.getMessage());
        }
        return 0L;
    }

    /**
     * 保存治疗记录
     *
     * @param treatmentInfoVos
     */
    public void operateTreatmentInfoRecord(List<TreatmentInfoVo> treatmentInfoVos) {
        if (CommonUtils.isNotEmpty(treatmentInfoVos)) {
            for (TreatmentInfoVo treatmentInfoVo : treatmentInfoVos) {
                try {
                    //报告id
                    String requestId = treatmentInfoVo.getRequestId();
                    //机构id
                    String reportOrganization = treatmentInfoVo.getReportOrganization();
                    if (CommonUtils.isNotEmpty(requestId) && CommonUtils.isNotEmpty(reportOrganization)) {
                        //根据治疗报告id和机构id查询是否已同步治疗记录
                        TreatmentRecordEntity treatmentRecordEntity = treatmentRecordDAO.getTreatmentRecordByRequestId(requestId, reportOrganization);
                        if (CommonUtils.isNotEmpty(treatmentRecordEntity)) {
                            //已经存在治疗记录，则不再进行保存
                            continue;
                        }
                        treatmentRecordEntity = new TreatmentRecordEntity();
                        BeanUtils.copy(treatmentInfoVo, treatmentRecordEntity);
                        String treatmentRecordId = UUID.randomUUID().toString();
                        treatmentRecordEntity.setTreatmentRecordId(treatmentRecordId);
                        treatmentRecordEntity.setBusinessType(treatmentInfoVo.getBusType());
                        treatmentRecordEntity.setRequestDatetime(CommonUtils.isEmpty(treatmentInfoVo.getRequestDateTime()) ? null : DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss", DateUtil.getStrTime(treatmentInfoVo.getRequestDateTime().replace("T", ""))));
                        treatmentRecordEntity.setReportDatetime(CommonUtils.isEmpty(treatmentInfoVo.getReportDateTime()) ? null : DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss", DateUtil.getStrTime(treatmentInfoVo.getReportDateTime().replace("T", ""))));
                        treatmentRecordEntity.setExecuteDatetime(CommonUtils.isEmpty(treatmentInfoVo.getExecuteDateTime()) ? null : DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss", DateUtil.getStrTime(treatmentInfoVo.getExecuteDateTime().replace("T", ""))));
                        treatmentRecordEntity.setReviewDatetime(CommonUtils.isEmpty(treatmentInfoVo.getReviewDateTime()) ? null : DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss", DateUtil.getStrTime(treatmentInfoVo.getReviewDateTime().replace("T", ""))));
                        treatmentRecordEntity.setCreateTime(new Date());
                        treatmentRecordDAO.save(treatmentRecordEntity);
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage());
                }
            }
        }
    }
/**============================================治疗信息同步结束===========================================**/

/**============================================用药信息同步开始===========================================**/
    /**
     * 同步用药信息
     *
     * @param organizationId
     * @param beginDate
     * @param endDate
     */
    private void pullPrescriptionRecords(String organizationId, String beginDate, String endDate) {
        QueryRecordRequest recordRequest = new QueryRecordRequest();
        recordRequest.setOrganizationId(organizationId);
        recordRequest.setBeginDate(beginDate);
        recordRequest.setEndDate(endDate);
        int pageNo = 1;
        recordRequest.setPageSize(2000);
        recordRequest.setPageNo(pageNo);
        Long total = syncPrescriptionRecordXml(recordRequest);
        if (total > recordRequest.getPageSize()) {
            Long size = total / recordRequest.getPageSize();
            for (int i = 0; i < size; i++) {
                pageNo++;
                recordRequest.setPageNo(pageNo);
                syncPrescriptionRecordXml(recordRequest);
            }
        }
    }

    /**
     * 同步用药信息
     *
     * @param request
     * @return
     */

    public Long syncPrescriptionRecordXml(QueryRecordRequest request) {
        String serviceName = PlatFormServiceEnum.QueryPrescriptionRecord.getServiceName();

        String msgType = PlatFormServiceEnum.QueryPrescriptionRecord.getServiceCode();
        //组装xml请求入参
        HisXmlRequest<QueryRecordRequest> req = new HisXmlRequest<>();
        req.setHeader(HisXmlHeader.Builder.custom()
                .organization(request.getOrganizationId())
                .sender("GOL")
                .serviceType(Constants.SERVICE_TYPE_SERVICE)
                .msgType(msgType)
                .build());
        req.setBody(request);
        try {
            PrescriptionRecordDataVo dataVo = ServiceController.instance().singleWork(serviceName, request.getOrganizationId(), req, PrescriptionRecordDataVo.class);
            if (null != dataVo) {
                List<PrescriptionRecordVo> records = dataVo.getRecords();
                operatePrescriptionRecord(records);
                return dataVo.getTotal();
            }
        } catch (ControllerException e) {
            logger.error("定时任务同步用药记录失败,失败原因:" + e.getMessage());
        }
        return 0L;
    }

    /**
     * 保存用药记录
     *
     * @param prescriptionRecordVos
     */
    private void operatePrescriptionRecord(List<PrescriptionRecordVo> prescriptionRecordVos) {
        if (CommonUtils.isNotEmpty(prescriptionRecordVos)) {
            for (PrescriptionRecordVo prescriptionRecordVo : prescriptionRecordVos) {
                try {
                    //业务记录号
                    String visitId = prescriptionRecordVo.getVisitId();
                    //机构id
                    String visitOrganization = prescriptionRecordVo.getVisitOrganization();
                    if (CommonUtils.isNotEmpty(visitId) && CommonUtils.isNotEmpty(visitOrganization)) {
                        PrescriptionRecordEntity prescriptionRecordEntity = prescriptionRecordDAO.getPrescriptionRecordByVisitId(visitId, visitOrganization);
                        //根据业务记录号和机构id获取用药记录
                        if (CommonUtils.isNotEmpty(prescriptionRecordEntity)) {
                            //已经存在用药记录，则不再进行保存
                            continue;
                        }
                        prescriptionRecordEntity = new PrescriptionRecordEntity();
                        BeanUtils.copy(prescriptionRecordVo, prescriptionRecordEntity);
                        String prescriptionRecordId = UUID.randomUUID().toString();
                        prescriptionRecordEntity.setPrescriptionRecordId(prescriptionRecordId);
                        prescriptionRecordEntity.setPrescriptionDate(CommonUtils.isEmpty(prescriptionRecordVo.getPrescriptionDate()) ? null : DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss", prescriptionRecordVo.getPrescriptionDate()));
                        prescriptionRecordEntity.setCreateTime(new Date());
                        prescriptionRecordDAO.save(prescriptionRecordEntity);
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage());
                }
            }
        }
    }

/**============================================用药信息同步结束===========================================**/
    /**
     * @description: 定时同步所有机构的门诊、住院、检验申请、检查申请、治疗记录、取药记录、手术记录
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/9/4 9:50
     */

//    @ScheduleJob(jobName = "syncHospitalVisitsRecord", cron = "0 0 1 * * ?", shardingTotalCount = 1, description =
//            "定时同步所有机构的门诊、住院、检验申请、检查申请、治疗记录、取药记录、手术记录", overwrite = true)
    public void syncHospitalVisitsRecord(JobParameter jobParameter) {

        ParamsOrgQo request = new ParamsOrgQo();
        request.setType(type);
        //查询所有机构
        BaseResponse listBaseResponse = baseDataService.queryOrganizationList(request);
        if (CommonUtils.isNotEmpty(listBaseResponse) && listBaseResponse.getCode() == ResultCode.SUCCESS && null != listBaseResponse.getData()) {
            List<Map> data = (List<Map>) listBaseResponse.getData();
            if (CommonUtils.isNotEmpty(data)) {
                for (Map datum : data) {
                    try {
                        //HIS服务地址
                        String hisUrl = (String) datum.get("hisUrl");
                        //检验服务地址
                        String examUrl = (String) datum.get("examUrl");
                        //检查服务地址
                        String checkUrl = (String) datum.get("checkUrl");
                        //机构代码
                        String organizationId = (String) datum.get("organizationId");
                        BasePropertyConfig basePropertyConfig = null;
                        if (CommonUtils.isNotEmpty(organizationId)) {
                            //获取专科随访his数据同步系统参数
                            basePropertyConfig = serviceOpenRpcService.getBasePropertyConfig("013107", organizationId);
                        }
                        String beginDate = "";
                        String endDate = "";
                        if (CommonUtils.isNotEmpty(basePropertyConfig)) {
                            beginDate = basePropertyConfig.getPropertyData() + "00:00:00";
                            endDate = basePropertyConfig.getPropertyData() + "23:59:59";
                        } else {
                            //TODO 如果系统参数查询不到，就查询当天的数据
                            String nowDate = DateUtil.formDate(new Date(), "yyyy-MM-dd");
                            beginDate = nowDate + " 00:00:00";
                            endDate = nowDate + " 23:59:59";
                        }
                        //手术记录
                        pullVrSurgicalRecords(organizationId, beginDate, endDate);
                        //检查报告
                        pullCheckReportRecords(organizationId, beginDate, endDate);
//                        //取药记录
//                        pullVrDispensingRecord(hisUrl, organizationId, beginDate, endDate);
//                        //检验申请单
//                        pullLabApplicationFormRecords(examUrl + Constants.INSPECTION_APPLICATION_RECORD, organizationId, beginDate, endDate);
//                        //检查申请单
//                        pullExamApplicationFormRecords(checkUrl + Constants.CHECK_APPLICATION_RECORD, organizationId, beginDate, endDate);
                        //治疗记录
                        pullTreatmentInfoRecords(organizationId, beginDate, endDate);
                        //用药记录
                        pullPrescriptionRecords(organizationId, beginDate, endDate);
                        //同步检验报告信息
                        pullInspectReportRecords(organizationId, beginDate, endDate);
                        //门诊记录
                        pullOutpatientRecords(organizationId, beginDate, endDate);
                        //住院记录
                        pullInpatientVisitRecords(organizationId, beginDate, endDate);
//                        syncApplicationFormRecord(checkUrl + Constants.TREATMENT_RECORD, organizationId, beginDate, endDate);
                        //同步诊断信息
//                        synDiagnosticInfo(organizationId);
                        //TODO 当天的数据处理完之后，就将系统参数进行更新
                        Date initDate = DateUtil.getDate(beginDate, "yyyy-MM-dd HH:mm:ss", null);
                        Date addDate = DateUtil.dateAddDay(initDate, 1);
                        //更新初始化参数的日期
                        serviceOpenRpcService.updateBasePropertyConfig(basePropertyConfig.getPropertyCode(),
                                basePropertyConfig.getObjectId(), DateUtil.formDate(addDate, "yyyy-MM-dd"));
                    } catch (Exception e) {
                        e.printStackTrace();
                        logger.error("同步就诊记录失败，失败原因=" + e.getMessage());
                    }
                }
            }
        }
    }

    /**
     * @Description: 同步取药记录-xml
     * @Author: zhaorb
     * @Date: 2020/12/11 14:52
     **/

    public Long syncVrDispensingRecordXml(QueryRecordRequest request) {
        logger.info("syncVrDispensingRecordXml入参：{}", JSONObject.toJSONString(request));
        BaseResponse baseResponse = new BaseResponse<>();
        //平台服务名称
        String serviceName = PlatFormServiceEnum.DISPENSING_RECORD.getServiceName();
        //参数中msgType
        String msgType = PlatFormServiceEnum.DISPENSING_RECORD.getServiceCode();
        //组装xml请求入参
        HisXmlRequest<QueryRecordRequest> req = new HisXmlRequest<>();
        req.setHeader(HisXmlHeader.Builder.custom()
                .organization(request.getOrganizationId())
                .sender("GOL")
                .serviceType(Constants.SERVICE_TYPE_SERVICE)
                .msgType(msgType)
                .build());
        req.setBody(request);
        try {
            PrescriptionRecordDataVo dataVo = ServiceController.instance().singleWork(serviceName, request.getOrganizationId(), req, PrescriptionRecordDataVo.class);
            if (null != dataVo) {
                List<PrescriptionRecordVo> records = dataVo.getRecords();
                operatePrescriptionRecord(records);
                return dataVo.getTotal();
            }
        } catch (ControllerException e) {
            logger.error("定时任务同步用药记录失败,失败原因:" + e.getMessage());
        }
        //参数头
        String msgHeaderXml = getMsgHeaderXml(HospitalVisitRecordTaskConstants.ORIGINORG, proSource, msgType);
        LinkedHashMap<String, String> queryConditions = new LinkedHashMap();
        queryConditions.put("VisitOrganization", request.getOrganizationId());
        queryConditions.put("BeginDateTime", request.getBeginDate());
        queryConditions.put("EndDateTime", request.getEndDate());
        queryConditions.put("PageNo", request.getPageNo() + "");
        queryConditions.put("PageSize", request.getPageSize() + "");
        String requestCon = WhisClientUtil.mapToXmlNull(queryConditions);
        String queryConditionsXml = getMsgBody(requestCon);
        //封装webservice入参
        String requestXml = getSoapXml(serviceName, msgHeaderXml + queryConditionsXml);
        logger.info("syncVrDispensingRecordXml入参：{}", requestXml);
        try {
            JSONObject jsonObjectBSXml = getJsonDataFromPhis(PHIS_PATH_URL, requestXml);
            JSONObject msgBody = jsonObjectBSXml.getJSONArray("MsgBody").getJSONObject(0);
            if ("true".equals(msgBody.getString("Status"))) {
                JSONObject datas = msgBody.getJSONArray("Data").getJSONObject(0);
                JSONObject record = datas.getJSONArray("Record").getJSONObject(0);
                JSONArray records = record.getJSONArray("Records");
                List<VrDispensingRecordResponse> list = JSONObject.parseArray(records.toJSONString(),
                        VrDispensingRecordResponse.class);
                if (CommonUtils.isNotEmpty(list)) {
                    for (VrDispensingRecordResponse recordResponse : list) {
                        try {
                            String clinicDistributionId = recordResponse.getDispensingRecordId();
                            String voOrganizationId = recordResponse.getVisitOrganization();

                            if (CommonUtils.isNotEmpty(clinicDistributionId) && CommonUtils.isNotEmpty(voOrganizationId)) {
                                //根据机构代码和取药记录查询是否已同步就诊记录
                                VrDispensingRecord vrDispensingRecord = vrDispensingRecordDAO.getVrDispensingRecord(clinicDistributionId, voOrganizationId);
                                //已存在取药记录，不再保存
                                if (null != vrDispensingRecord) {
                                    continue;
                                }

                                vrDispensingRecord = new VrDispensingRecord();
                                //字段装换
                                vrDispensingRecord.setClinicDistributionId(recordResponse.getDispensingRecordId());
                                vrDispensingRecord.setPharmacyCode(recordResponse.getPharmacyCode());
                                vrDispensingRecord.setPharmacyName(recordResponse.getPharmacyName());
                                vrDispensingRecord.setDispensingDate(CommonUtils.isEmpty(recordResponse.getDispensingDateTime()) ? null : DateUtil.getDateTime(
                                        "yyyy-MM-dd HH:mm:ss", recordResponse.getDispensingDateTime()));
                                vrDispensingRecord.setPrescriptionId(recordResponse.getPrescriptionRecordId());
                                vrDispensingRecord.setPrescriptionTime(CommonUtils.isEmpty(recordResponse.getPrescriptionDate()) ? null : DateUtil.getDateTime(
                                        "yyyy-MM-dd HH:mm:ss", recordResponse.getPrescriptionDate()));
                                vrDispensingRecord.setPrescriptionType(recordResponse.getRecipeTypeCode());
                                vrDispensingRecord.setInvoiceNumber(recordResponse.getInvoiceCode());
                                vrDispensingRecord.setPatientType(recordResponse.getPatientType());
                                vrDispensingRecord.setPatientNature(recordResponse.getPatientProperties());
                                vrDispensingRecord.setInvoiceNumber(recordResponse.getInvoiceCode());
                                vrDispensingRecord.setPatientId(recordResponse.getSourcePatientId());
                                vrDispensingRecord.setPatientName(recordResponse.getName());
                                vrDispensingRecord.setPatientSex(recordResponse.getSex());
                                vrDispensingRecord.setPatientBirthday(CommonUtils.isEmpty(recordResponse.getBirthDate()) ? null : DateUtil.getDateTime(
                                        "yyyy-MM-dd HH:mm:ss", recordResponse.getBirthDate()));
                                vrDispensingRecord.setPatientAge(Byte.valueOf(recordResponse.getAge().replace("岁", "")));
                                vrDispensingRecord.setCardType(recordResponse.getIdCardCode());
                                vrDispensingRecord.setCardNumber(recordResponse.getIdCard());
                                vrDispensingRecord.setPatientMedicalCardType(recordResponse.getMedicalCardType());
                                vrDispensingRecord.setPatientMedicalCardNumber(recordResponse.getMedicalCardId());
                                vrDispensingRecord.setTelephone(recordResponse.getContactNo());
                                vrDispensingRecord.setAddress(recordResponse.getLiveAddrHouseNumber());
                                vrDispensingRecord.setOrganizationId(recordResponse.getVisitOrganization());
                                vrDispensingRecord.setOrganizationName(recordResponse.getVisitOrganizationName());
                                vrDispensingRecord.setDepartmentId(recordResponse.getDeptCode());
                                vrDispensingRecord.setDepartmentName(recordResponse.getDeptName());
                                vrDispensingRecord.setDoctorId(recordResponse.getDoctorId());
                                vrDispensingRecord.setDoctorName(recordResponse.getDoctorName());
                                vrDispensingRecord.setIdentificationNumber("");
                                vrDispensingRecord.setWindowName("");
                                vrDispensingRecord.setWindowNumber("");
                                vrDispensingRecord.setSatisfactionStatus("0");

                                String distributionId = UUID.randomUUID().toString();
                                vrDispensingRecord.setDistributionId(distributionId);
                                vrDispensingRecord.setCreateTime(new Date());
                                vrDispensingRecordDAO.save(vrDispensingRecord);
                            }
                        } catch (Exception e) {
                            logger.error(e.getMessage());
                        }
                    }
                    return Long.valueOf(list.size());
                }

            } else {
                logger.error("定时任务同步取药记录失败,MegBody节点为空");
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("定时任务同步取药记录失败");

        }
        return 0L;
    }


    /**
     * @description: 同步检验检查记录
     */
    public void syncApplicationFormRecord(String url, String organizationId, String beginDate, String endDate) {
        Map request = new HashMap();
        request.put("organizationId", organizationId);
        request.put("beginDate", beginDate);
        request.put("endDate", endDate);
        try {
            JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(request));
            JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(url, jsonParams);
            Integer code = jsonObject.getInteger("code");
            if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") &&
                    jsonObject.get("data") != null && !jsonObject.getJSONArray("data").isEmpty()) {
                String data = jsonObject.get("data").toString();
                List<ApplicationFormRecordVo> applicationFormRecordVos = JSONArray.parseArray(data, ApplicationFormRecordVo.class);
                operateApplicationFormRecordList(applicationFormRecordVos);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * @description: 查询检验申请单列表
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/12/16 15:25
     * @param: requeat
     * @return: java.lang.Long
     */
    public Long syncLabListForXML(QueryLabRecordRequest requeat) {
        Long total = 0L;
        List<ApplicationFormRecordVo> applicationFormRecordVos = this.getLabListForXML(requeat);
        if (CommonUtils.isNotEmpty(applicationFormRecordVos)) {
            operateApplicationFormRecordList(applicationFormRecordVos);
            total = Long.valueOf(applicationFormRecordVos.size());
        }
        return total;
    }

    /**
     * @description: 查询检验申请单列表
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/12/16 15:25
     * @param: requeat
     * @return: java.lang.Long
     */
    public List<ApplicationFormRecordVo> getLabListForXML(QueryLabRecordRequest request) {
        List<ApplicationFormRecordVo> applicationFormRecordVos = new ArrayList<>();
        Long total = 0L;
        logger.info("检验申请单列表请求入参=" + JSONUtils.writeValueAsString(request));
        String serviceName = PlatFormServiceEnum.LAB_REPORT_BATCH_QUERY.getServiceName();
        String msgType = PlatFormServiceEnum.LAB_REPORT_BATCH_QUERY.getServiceCode();
        //组装xml请求入参
        HisXmlRequest<QueryLabRecordRequest> req = new HisXmlRequest<>();
        req.setHeader(HisXmlHeader.Builder.custom()
                .organization(request.getVisit().getVisitOrganization())
                .sender("GOL")
                .serviceType(Constants.SERVICE_TYPE_SERVICE)
                .msgType(msgType)
                .build());
        req.setBody(request);
        try {
            QueryLabRecordResponse labRecordResponse = ServiceController.instance().singleWork(serviceName, request.getVisit().getVisitOrganization(), req, QueryLabRecordResponse.class);
            if (null != labRecordResponse) {
                applicationFormRecordVos = transformLabFormRecord(labRecordResponse);
            }
        } catch (ControllerException e) {
            logger.error("定时任务获取检验申请单失败，失败原因:" + e.getMessage());
        }
        return applicationFormRecordVos;
    }


    /**
     * @description: 同步检查xml记录
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/12/15 12:53
     * @param: request
     * @return: java.lang.Long
     */
    public Long syncExamFormRecordXml(QueryExamRecordRequest request) {
        Long total = 0L;
        ExamFormRecordList formRecordList = this.getExamFormRecordXML(request);
        if (CommonUtils.isNotEmpty(formRecordList)) {
            total = formRecordList.getTotal();
        }
        return total;
    }


    public ExamFormRecordList getExamFormRecordXML(QueryExamRecordRequest request) {
        ExamFormRecordList dataVo = new ExamFormRecordList();
        String serviceName = PlatFormServiceEnum.APPLY_FORM_LIST.getServiceName();
        String msgType = PlatFormServiceEnum.APPLY_FORM_LIST.getServiceCode();
        //组装xml请求入参
        HisXmlRequest<QueryExamRecordRequest> req = new HisXmlRequest<>();
        req.setHeader(HisXmlHeader.Builder.custom()
                .organization(request.getOrganizationId())
                .sender("GOL")
                .serviceType(Constants.SERVICE_TYPE_SERVICE)
                .msgType(msgType)
                .build());
        req.setBody(request);
        try {
            dataVo = ServiceController.instance().singleWork(serviceName, request.getOrganizationId(), req, ExamFormRecordList.class);
            List<ApplicationFormRecordVo> applicationFormRecordVos = transformExamFormRecord(dataVo);
            if (CommonUtils.isNotEmpty(applicationFormRecordVos)) {
                operateApplicationFormRecordList(applicationFormRecordVos);
            }
        } catch (ControllerException e) {
            logger.error("定时任务检查申请单记录信息，失败原因:" + e.getMessage());
        }
        return dataVo;
    }


    /**
     * @description: 转换检验记录回参
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/12/15 12:52
     * @param: dataVo
     * @return: java.util.List<visitrecord.bean.vo.ApplicationFormRecordVo>
     */
    public List<ApplicationFormRecordVo> transformLabFormRecord(QueryLabRecordResponse dataVo) {
        List<ApplicationFormRecordVo> applicationFormRecordVos = null;
        if (null != dataVo) {
            List<QueryLabRecordResponse.LabRequest> applyInfoList = dataVo.getLabRequests();
            if (CommonUtils.isNotEmpty(applyInfoList)) {
                applicationFormRecordVos = new ArrayList<>();
                ApplicationFormRecordVo applicationFormRecordVo = null;
                List<VrApplicationFormDetail> details;
                VrApplicationFormDetail detail;
                for (QueryLabRecordResponse.LabRequest applyInfo : applyInfoList) {
                    applicationFormRecordVo = new ApplicationFormRecordVo();
                    applicationFormRecordVo.setCompanionName("");
                    applicationFormRecordVo.setCompanionRelationship("");
                    applicationFormRecordVo.setCompanionPhone("");
                    applicationFormRecordVo.setApplicationId(UUID.randomUUID().toString());
                    applicationFormRecordVo.setApplicationNo(applyInfo.getRequestId());
                    applicationFormRecordVo.setApplicationTime(new Date());
                    applicationFormRecordVo.setApplicant("");
                    //1:检验  2:检查  3:处置
                    applicationFormRecordVo.setBillCategoryCode("1");
                    applicationFormRecordVo.setApplicationFormStatus(String.valueOf(applyInfo.getRequestStatus()));
                    applicationFormRecordVo.setPatientType(applyInfo.getPatientType());
                    applicationFormRecordVo.setPatientNature(applyInfo.getPatientProperties());
                    applicationFormRecordVo.setPatientId(applyInfo.getSourcePatientId());
                    applicationFormRecordVo.setPatientName(applyInfo.getName());
                    applicationFormRecordVo.setPatientSex(applyInfo.getSex());
                    if (!StringUtils.isEmpty(applyInfo.getBirthDate())) {
                        applicationFormRecordVo.setPatientBirthday(CommonUtils.isEmpty(applyInfo.getBirthDate()) ? null : DateUtil.getDateTime("yyyy-MM-dd", operateDate(applyInfo.getBirthDate())));
                    }
                    //若是年龄不为空，那么就添加年龄
                    if (CommonUtils.isNotEmpty(applyInfo.getAge())) {
                        applicationFormRecordVo.setPatientAge(Byte.valueOf(applyInfo.getAge()));
                        applicationFormRecordVo.setAgeUnit("岁");
                        applicationFormRecordVo.setPatientAgeText(applyInfo.getAge() + "岁");
                        //若是年龄为空，周岁不为空，那么就取周岁
                    } else if (CommonUtils.isNotEmpty(applyInfo.getMonthAge())) {
                        applicationFormRecordVo.setPatientAge(Byte.valueOf(applyInfo.getMonthAge()));
                        applicationFormRecordVo.setAgeUnit("周岁");
                        applicationFormRecordVo.setPatientAgeText(applyInfo.getMonthAge() + "周岁");
                    }

                    applicationFormRecordVo.setCardType("01");
                    applicationFormRecordVo.setCardNumber(applyInfo.getIdCard());
                    applicationFormRecordVo.setPatientMedicalCardType(applyInfo.getMedicalCardType());
                    applicationFormRecordVo.setPatientMedicalCardNumber(applyInfo.getMedicalCardId());
                    applicationFormRecordVo.setTelephone(applyInfo.getPatientPhone());
                    applicationFormRecordVo.setAddress(applyInfo.getAddress());
                    applicationFormRecordVo.setSection(applyInfo.getRequestDept());
                    applicationFormRecordVo.setBedNumber(applyInfo.getSickbedId());
                    applicationFormRecordVo.setOrganizationId(applyInfo.getVisitOrganization());
//                    applicationFormRecordVo.setOrganizationName(applyInfo.get());
                    applicationFormRecordVo.setOpenTime(CommonUtils.isEmpty(applyInfo.getRequestDateTime()) ? null : DateUtil.getDateTime("yyyy-MM-dd", operateDate(applyInfo.getRequestDateTime())));
                    applicationFormRecordVo.setOpenDoctorId(applyInfo.getRequestDoctor());
                    applicationFormRecordVo.setOpenDoctorName(applyInfo.getRequestDoctorName());
                    applicationFormRecordVo.setOpenDepartmentId(applyInfo.getRequestDept());
                    applicationFormRecordVo.setOpenDepartmentName(applyInfo.getRequestDeptName());
                    //紧急标志 0 不紧急 1 紧急
                    applicationFormRecordVo.setEmergencyMode(applyInfo.getIsEmergency());
//                    applicationFormRecordVo.setAmount(StringUtils.isEmpty(applyInfo.getExamCost())?new BigDecimal("0"):new BigDecimal(examRequest.getExamCost()));
                    applicationFormRecordVo.setExecutiveTime(CommonUtils.isEmpty(applyInfo.getExamExecuteTime()) ? null : DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss", operateDate(applyInfo.getExamExecuteTime())));
                    applicationFormRecordVo.setExecutiveDoctorId("");
                    applicationFormRecordVo.setExecutiveDoctorName("");
                    applicationFormRecordVo.setExecutiveDepartmentId(applyInfo.getExamExecuteDept());
                    applicationFormRecordVo.setExecutiveDepartmentName(applyInfo.getExamExecuteDeptName());
                    applicationFormRecordVo.setAuditTime(null);
                    applicationFormRecordVo.setAuditDoctorId(applyInfo.getAuditDoctorCode());
                    applicationFormRecordVo.setAuditDoctorName(applyInfo.getAuditDoctorName());
                    applicationFormRecordVo.setReportTime(null);
                    applicationFormRecordVo.setReportDoctorId("");
                    applicationFormRecordVo.setReportDoctorName("");
                    applicationFormRecordVo.setCancelDoctorId("");
                    applicationFormRecordVo.setCancelDoctorName("");
                    applicationFormRecordVo.setCancelTime(null);
                    applicationFormRecordVo.setInvoiceNumber("");
                    applicationFormRecordVo.setSatisfactionStatus("0");
                    applicationFormRecordVo.setSurveyNumber(0);
                    applicationFormRecordVo.setFinishNumber(0);

                    if (CommonUtils.isNotEmpty(applyInfo.getItems())) {
                        details = new ArrayList<>();
                        for (QueryLabRecordResponse.LabRequest.Item item : applyInfo.getItems()) {
                            detail = new VrApplicationFormDetail();
                            detail.setItemId(item.getItemCode());
                            detail.setItemName(item.getItemName());
                            // 1:检验  2:检查  3:处置
                            detail.setItemType("1");
                            details.add(detail);
                        }
                        applicationFormRecordVo.setDetails(details);
                    }
                    applicationFormRecordVos.add(applicationFormRecordVo);
                }
            }
        }
        return applicationFormRecordVos;
    }

    /**
     * @description: 处理时间
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/12/16 19:39
     */
    public String operateDate(String dateTime) {
        if (CommonUtils.isNotEmpty(dateTime)) {
            if (dateTime.length() > 19) {
                dateTime = dateTime.substring(0, 19);
            }
        } else {
            dateTime = "";
        }
        return dateTime;
    }

    /**
     * @description: 转换检查记录回参
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/12/15 12:52
     * @param: dataVo
     * @return: java.util.List<visitrecord.bean.vo.ApplicationFormRecordVo>
     */
    public List<ApplicationFormRecordVo> transformExamFormRecord(ExamFormRecordList dataVo) {
        List<ApplicationFormRecordVo> applicationFormRecordVos = null;
        if (null != dataVo) {
            Long total = dataVo.getTotal();
            List<ExamFormRecordList.ApplyInfo> applyInfoList = dataVo.getApplyInfoList();
            if (CommonUtils.isNotEmpty(applyInfoList)) {
                applicationFormRecordVos = new ArrayList<>();
                ApplicationFormRecordVo applicationFormRecordVo = null;
                List<VrApplicationFormDetail> details;
                VrApplicationFormDetail detail;
                for (ExamFormRecordList.ApplyInfo applyInfo : applyInfoList) {
                    applicationFormRecordVo = new ApplicationFormRecordVo();
                    ExamFormRecordList.ApplyInfo.Patient patient = applyInfo.getPatient();
                    ExamFormRecordList.ApplyInfo.Visit visit = applyInfo.getVisit();
                    ExamFormRecordList.ApplyInfo.ExamRequest examRequest = applyInfo.getExamRequest();

                    applicationFormRecordVo.setCompanionName("");
                    applicationFormRecordVo.setCompanionRelationship("");
                    applicationFormRecordVo.setCompanionPhone("");
                    applicationFormRecordVo.setApplicationId(UUID.randomUUID().toString());
                    applicationFormRecordVo.setApplicationNo(examRequest.getRequestId());
                    applicationFormRecordVo.setApplicationTime(new Date());
                    applicationFormRecordVo.setApplicant("");
                    //1:检验  2:检查  3:处置
                    applicationFormRecordVo.setBillCategoryCode("2");
                    applicationFormRecordVo.setApplicationFormStatus("");
                    applicationFormRecordVo.setPatientType(visit.getPatientType());
                    applicationFormRecordVo.setPatientNature("");
                    applicationFormRecordVo.setPatientId(patient.getSourcePatientId());
                    applicationFormRecordVo.setPatientName(patient.getName());
                    applicationFormRecordVo.setPatientSex(patient.getSex());
                    applicationFormRecordVo.setPatientBirthday(DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss", operateDate(
                            StringUtils.isEmpty(patient.getBirthDate()) ? "1900-01-01 00:00:00" : patient.getBirthDate().substring(0, patient.getBirthDate().lastIndexOf(".")))));
//                    applicationFormRecordVo.setPatientAge(DateUtil.getAge(DateUtil.getDateTime(patient.getBirthDate(),"yyyy-MM-dd HH:mm:ss")));
                    applicationFormRecordVo.setAgeUnit("岁");
                    applicationFormRecordVo.setCardType(patient.getIdCardCode());
                    applicationFormRecordVo.setCardNumber(patient.getIdCard());
                    applicationFormRecordVo.setPatientMedicalCardType(visit.getMedicalCardType());
                    applicationFormRecordVo.setPatientMedicalCardNumber(visit.getMedicalCardId());
                    applicationFormRecordVo.setTelephone(patient.getPatientPhone());
                    applicationFormRecordVo.setAddress(examRequest.getAddress());
                    applicationFormRecordVo.setSection(examRequest.getDept());
                    applicationFormRecordVo.setBedNumber(examRequest.getSickbedId());
                    applicationFormRecordVo.setOrganizationId(visit.getVisitOrganization());
                    applicationFormRecordVo.setOrganizationName("");
                    applicationFormRecordVo.setOpenTime(new Date());
                    applicationFormRecordVo.setOpenDoctorId(examRequest.getRequestDoctor());
                    applicationFormRecordVo.setOpenDoctorName(examRequest.getRequestDoctorName());
                    applicationFormRecordVo.setOpenDepartmentId(examRequest.getRequestDept());
                    applicationFormRecordVo.setOpenDepartmentName(examRequest.getRequestDeptName());
                    //紧急标志 0 不紧急 1 紧急
                    applicationFormRecordVo.setEmergencyMode(examRequest.getIsEmergency());
                    applicationFormRecordVo.setAmount(StringUtils.isEmpty(examRequest.getExamCost()) ? new BigDecimal("0") : new BigDecimal(examRequest.getExamCost()));
                    applicationFormRecordVo.setExecutiveTime(DateUtil.getDateTime("yyyy-MM-dd HH:mm:ss", operateDate(
                            StringUtils.isEmpty(examRequest.getExecuteDateTime()) ? "1900-01-01 00:00:00" : examRequest.getExecuteDateTime())));
                    applicationFormRecordVo.setExecutiveDoctorId("");
                    applicationFormRecordVo.setExecutiveDoctorName("");
                    applicationFormRecordVo.setExecutiveDepartmentId(examRequest.getExamExecuteDept());
                    applicationFormRecordVo.setExecutiveDepartmentName(examRequest.getExamExecuteDeptName());
                    applicationFormRecordVo.setAuditTime(null);
                    applicationFormRecordVo.setAuditDoctorId(examRequest.getAuditDoctor());
                    applicationFormRecordVo.setAuditDoctorName(examRequest.getAuditDoctorName());
                    applicationFormRecordVo.setReportTime(null);
                    applicationFormRecordVo.setReportDoctorId("");
                    applicationFormRecordVo.setReportDoctorName("");
                    applicationFormRecordVo.setCancelDoctorId("");
                    applicationFormRecordVo.setCancelDoctorName("");
                    applicationFormRecordVo.setCancelTime(new Date());
                    applicationFormRecordVo.setInvoiceNumber("");
                    applicationFormRecordVo.setSatisfactionStatus("0");
                    applicationFormRecordVo.setSurveyNumber(0);
                    applicationFormRecordVo.setFinishNumber(0);

                    if (CommonUtils.isNotEmpty(examRequest.getItemList())) {
                        details = new ArrayList<>();
                        for (ExamFormRecordList.ApplyInfo.ExamRequest.Item item : examRequest.getItemList()) {
                            detail = new VrApplicationFormDetail();
                            detail.setItemId(item.getItemCode());
                            detail.setItemName(item.getItemName());
                            // 1:检验  2:检查  3:处置
                            detail.setItemType("2");
                            details.add(detail);
                        }
                        applicationFormRecordVo.setDetails(details);
                    }
                    applicationFormRecordVos.add(applicationFormRecordVo);
                }
            }
        }
        return applicationFormRecordVos;
    }

    /**
     * @description: 处理检验、检查、治疗申请记录
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/12/13 10:19
     * @param: applicationFormRecordVos
     * @return: void
     */
    public void operateApplicationFormRecordList(List<ApplicationFormRecordVo> applicationFormRecordVos) {
        if (CommonUtils.isNotEmpty(applicationFormRecordVos)) {
            for (ApplicationFormRecordVo applicationFormRecordVo : applicationFormRecordVos) {
                try {
                    String applicationNo = applicationFormRecordVo.getApplicationNo();
                    String voOrganizationId = applicationFormRecordVo.getOrganizationId();

                    if (CommonUtils.isNotEmpty(applicationNo) && CommonUtils.isNotEmpty(voOrganizationId)) {
                        //根据机构代码和申请单号查询是否已同步就诊记录
                        VrApplicationFormRecord vrApplicationFormRecord = vrApplicationFormRecordDAO.getVrApplicationFormRecord(applicationNo, voOrganizationId);
                        //已存在申请记录，不再保存
                        if (null != vrApplicationFormRecord) {
                            continue;
                        }
                        vrApplicationFormRecord = new VrApplicationFormRecord();
                        BeanUtils.copy(applicationFormRecordVo, vrApplicationFormRecord);
                        String applicationId = UUID.randomUUID().toString();
                        vrApplicationFormRecord.setApplicationId(applicationId);
                        vrApplicationFormRecord.setCreateTime(new Date());
                        vrApplicationFormRecordDAO.save(vrApplicationFormRecord);

                        List<VrApplicationFormDetail> details = applicationFormRecordVo.getDetails();

                        if (CommonUtils.isNotEmpty(details)) {
                            for (VrApplicationFormDetail vrApplicationFormDetail : details) {
                                String applicationDetailId = UUID.randomUUID().toString();
                                vrApplicationFormDetail.setApplicationDetailId(applicationDetailId);
                                vrApplicationFormDetail.setApplicationId(vrApplicationFormRecord.getApplicationId());
                                vrApplicationFormDetail.setApplicationNo(vrApplicationFormRecord.getApplicationNo());
                                vrApplicationFormDetailDAO.save(vrApplicationFormDetail);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage());
                }
            }
        }
    }


    /**
     * @description: 同步取药记录
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/1/4 11:22
     * @param: hisUrl
     * @param: organizationId
     * @param: beginDate
     * @param: endDate
     * @return: void
     */
    public void pullVrDispensingRecord(String hisUrl, String organizationId, String beginDate, String endDate) {
        //json拉取
//        syncVrDispensingRecord(hisUrl, organizationId, beginDate, endDate);
        //xml拉取
        QueryRecordRequest recordRequest = new QueryRecordRequest();
        recordRequest.setOrganizationId(organizationId);
        recordRequest.setBeginDate(beginDate);
        recordRequest.setEndDate(endDate);

        int pageNo = 1;
        recordRequest.setPageSize(2000);
        Long total = syncVrDispensingRecordXml(recordRequest);
        if (total > recordRequest.getPageSize()) {
            long size = total / recordRequest.getPageSize();
            for (long i = 0; i < size; i++) {
                pageNo++;
                recordRequest.setPageNo(pageNo);
                syncVrDispensingRecordXml(recordRequest);
            }
        }
    }

    /**
     * @description: 同步检验申请单
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/1/4 11:22
     * @param: hisUrl
     * @param: organizationId
     * @param: beginDate
     * @param: endDate
     * @return: void
     */
    public void pullLabApplicationFormRecords(String organizationId, String beginDate, String endDate) {
        //json拉取
//        syncApplicationFormRecord(hisUrl, organizationId, beginDate, endDate);
        //xml拉取
        QueryLabRecordRequest labRecordRequest = new QueryLabRecordRequest();
        QueryLabRecordRequest.InnerVisit visit = new QueryLabRecordRequest.InnerVisit();
        visit.setVisitOrganization(organizationId);
        labRecordRequest.setVisit(visit);
        QueryLabRecordRequest.InnerLabRequest labRequest = new QueryLabRecordRequest.InnerLabRequest();
        int pageNo = 1;
        labRequest.setEffectiveTimeLow(beginDate);
        labRequest.setEffectiveTimeHigh(endDate);
        labRequest.setRequestStatus("4");
        labRequest.setPageNo(pageNo);
        labRequest.setPageSize(2000);
        labRecordRequest.setLabRequest(labRequest);

        Long total = syncLabListForXML(labRecordRequest);
        if (total > labRequest.getPageSize()) {
            long size = total / labRequest.getPageSize();
            for (long i = 0; i < size; i++) {
                pageNo++;
                labRequest.setPageNo(pageNo);
                labRecordRequest.setLabRequest(labRequest);
                syncLabListForXML(labRecordRequest);
            }
        }
    }

    /**
     * @description: 同步检查申请单
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/1/4 11:22
     * @param: hisUrl
     * @param: organizationId
     * @param: beginDate
     * @param: endDate
     * @return: void
     */
    public void pullExamApplicationFormRecords(String organizationId, String beginDate, String endDate) {
        //json拉取
        //syncApplicationFormRecord(hisUrl, organizationId, beginDate, endDate);
        //xml拉取
        QueryExamRecordRequest queryExamRecordRequest = new QueryExamRecordRequest();
        queryExamRecordRequest.setOrganizationId(organizationId);
        //时间类型 1.检查日期（RIS登记日期）范围查询
        queryExamRecordRequest.setTimeType("1");
        //检查项目状态代码  3 已检查
        queryExamRecordRequest.setItemStatus("3");
        queryExamRecordRequest.setBeginDate(beginDate);
        queryExamRecordRequest.setEndDate(endDate);
        int pageNo = 1;
        queryExamRecordRequest.setPageSize(2000);

        Long total;

        queryExamRecordRequest.setPageSize(2000);
        queryExamRecordRequest.setPageNo(pageNo);
        total = syncExamFormRecordXml(queryExamRecordRequest);
        if (total > queryExamRecordRequest.getPageSize()) {
            Long size = total / queryExamRecordRequest.getPageSize();
            for (int i = 0; i < size; i++) {
                pageNo++;
                queryExamRecordRequest.setPageNo(pageNo);
                syncExamFormRecordXml(queryExamRecordRequest);
            }
        }
    }


    /**
     * @description: 同步就诊记录
     */
    public void syncOutpatientRecords(String hisUrl, String organizationId, String beginDate, String endDate) {
        Map request = new HashMap();
        request.put("organizationId", organizationId);
        request.put("beginDate", beginDate);
        request.put("endDate", endDate);
        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(request));
        JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(hisUrl + Constants.OUTPATIENT_VISIT_RECORD, jsonParams);
        Integer code = jsonObject.getInteger("code");
        if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") &&
                jsonObject.get("data") != null && !jsonObject.getJSONArray("data").isEmpty()) {
            String data = jsonObject.get("data").toString();
            List<OutpatientRecordVo> outpatientRecordVoList = JSONArray.parseArray(data, OutpatientRecordVo.class);
            operateOutpatientRecordVoList(outpatientRecordVoList);
        }
    }


    /**
     * 更新businessId
     *
     * @param businessType
     * @param visitNo
     * @param vrOutpatientVisitRecord
     */
    public void updateBusinessId(String businessType, String visitNo, VrOutpatientVisitRecord vrOutpatientVisitRecord) {
        List<VrSurgicalRecord> vrSurgicalRecordList = vrSurgicalRecordDAO.queryVrSurgicalRecordList(businessType, visitNo);
        List<ExamReportEntity> examReportList = examReportDAO.queryExamReportEntityList(businessType, visitNo);
        List<TreatmentRecordEntity> treatmentRecordList = treatmentRecordDAO.queryTreatmentRecordEntityList(businessType, visitNo);
        List<PrescriptionRecordEntity> prescriptionRecordList = prescriptionRecordDAO.queryPrescriptionRecordEntityList(businessType, visitNo);
        List<InspectReportRecordEntity> inspectReportRecordList = inspectReportRecordDAO.queryInspectReportRecordEntityList(businessType, visitNo);
        //手术记录
        if (CommonUtils.isNotEmpty(vrSurgicalRecordList)) {
            for (VrSurgicalRecord vrSurgicalRecord : vrSurgicalRecordList) {
                if (businessType.equals(vrSurgicalRecord.getBusinessType()) && visitNo.equals(vrSurgicalRecord.getVisitId())) {
                    vrSurgicalRecord.setBusinessId(vrOutpatientVisitRecord.getVisitRecordId());
                    vrSurgicalRecordDAO.update(vrSurgicalRecord);
                }
            }
        }
        //检查报告
        if (CommonUtils.isNotEmpty(examReportList)) {
            for (ExamReportEntity examReport : examReportList) {
                if (businessType.equals(examReport.getBusinessType()) && visitNo.equals(examReport.getVisitId())) {
                    examReport.setBusinessId(vrOutpatientVisitRecord.getVisitRecordId());
                    examReportDAO.update(examReport);
                }
            }
        }
        //治疗信息
        if (CommonUtils.isNotEmpty(treatmentRecordList)) {
            for (TreatmentRecordEntity treatmentRecord : treatmentRecordList) {
                if (businessType.equals(treatmentRecord.getBusinessType()) && visitNo.equals(treatmentRecord.getVisitId())) {
                    treatmentRecord.setBusinessId(vrOutpatientVisitRecord.getVisitRecordId());
                    treatmentRecordDAO.update(treatmentRecord);
                }
            }
        }
        //用药信息
        if (CommonUtils.isNotEmpty(prescriptionRecordList)) {
            for (PrescriptionRecordEntity prescriptionRecord : prescriptionRecordList) {
                if (businessType.equals(prescriptionRecord.getBusinessType()) && visitNo.equals(prescriptionRecord.getVisitId())) {
                    prescriptionRecord.setBusinessId(vrOutpatientVisitRecord.getVisitRecordId());
                    prescriptionRecordDAO.update(prescriptionRecord);
                }
            }
        }
        //检验报告
        if (CommonUtils.isNotEmpty(inspectReportRecordList)) {
            for (InspectReportRecordEntity inspectReportRecord : inspectReportRecordList) {
                if (businessType.equals(inspectReportRecord.getBusinessType()) && visitNo.equals(inspectReportRecord.getVisitId())) {
                    inspectReportRecord.setBusinessId(vrOutpatientVisitRecord.getVisitRecordId());
                    inspectReportRecordDAO.update(inspectReportRecord);
                }
            }
        }
    }


    /**
     * @description: 同步住院记录
     */
    public void syncInpatientVisitRecord(String hisUrl, String organizationId, String beginDate, String endDate) {
        Map request = new HashMap();
        request.put("organizationId", organizationId);
        request.put("beginDate", beginDate);
        request.put("endDate", endDate);
        JSONObject jsonParams = JSONObject.parseObject(JSONObject.toJSONString(request));
        JSONObject jsonObject = KdHttpClientUtil.doPostJSONRequest(hisUrl + Constants.INPATIENT_VISIT_RECORD, jsonParams);
        Integer code = jsonObject.getInteger("code");
        if (jsonObject.getInteger("code") == ResultCode.SUCCESS && jsonObject.containsKey("data") &&
                jsonObject.get("data") != null && !jsonObject.getJSONArray("data").isEmpty()) {
            String data = jsonObject.get("data").toString();
            List<InpatientVisitRecordVo> inpatientVisitRecordVos = JSONArray.parseArray(data, InpatientVisitRecordVo.class);
            operateInpatientVisitRecord(inpatientVisitRecordVos);
        }
    }


    /**
     * 更新businessId
     *
     * @param businessType
     * @param visitNo
     * @param vrInpatientVisitRecord
     */
    public void updateBusinessIdByHospital(String businessType, String visitNo, VrInpatientVisitRecord vrInpatientVisitRecord) {
        List<VrSurgicalRecord> vrSurgicalRecordList = vrSurgicalRecordDAO.queryVrSurgicalRecordList(businessType, visitNo);
        List<ExamReportEntity> examReportList = examReportDAO.queryExamReportEntityList(businessType, visitNo);
        List<TreatmentRecordEntity> treatmentRecordList = treatmentRecordDAO.queryTreatmentRecordEntityList(businessType, visitNo);
        List<PrescriptionRecordEntity> prescriptionRecordList = prescriptionRecordDAO.queryPrescriptionRecordEntityList(businessType, visitNo);
        List<InspectReportRecordEntity> inspectReportRecordList = inspectReportRecordDAO.queryInspectReportRecordEntityList(businessType, visitNo);
        //手术记录
        if (CommonUtils.isNotEmpty(vrSurgicalRecordList)) {
            for (VrSurgicalRecord vrSurgicalRecord : vrSurgicalRecordList) {
                if (businessType.equals(vrSurgicalRecord.getBusinessType()) && visitNo.equals(vrSurgicalRecord.getVisitId())) {
                    vrSurgicalRecord.setBusinessId(vrInpatientVisitRecord.getHospitalRecordId());
                    vrSurgicalRecordDAO.update(vrSurgicalRecord);
                }
            }
        }
        //检查报告
        if (CommonUtils.isNotEmpty(examReportList)) {
            for (ExamReportEntity examReport : examReportList) {
                if (businessType.equals(examReport.getBusinessType()) && visitNo.equals(examReport.getVisitId())) {
                    examReport.setBusinessId(vrInpatientVisitRecord.getHospitalRecordId());
                    examReportDAO.update(examReport);
                }
            }
        }
        //治疗信息
        if (CommonUtils.isNotEmpty(treatmentRecordList)) {
            for (TreatmentRecordEntity treatmentRecord : treatmentRecordList) {
                if (businessType.equals(treatmentRecord.getBusinessType()) && visitNo.equals(treatmentRecord.getVisitId())) {
                    treatmentRecord.setBusinessId(vrInpatientVisitRecord.getHospitalRecordId());
                    treatmentRecordDAO.update(treatmentRecord);
                }
            }
        }
        //用药信息
        if (CommonUtils.isNotEmpty(prescriptionRecordList)) {
            for (PrescriptionRecordEntity prescriptionRecord : prescriptionRecordList) {
                if (businessType.equals(prescriptionRecord.getBusinessType()) && visitNo.equals(prescriptionRecord.getVisitId())) {
                    prescriptionRecord.setBusinessId(vrInpatientVisitRecord.getHospitalRecordId());
                    prescriptionRecordDAO.update(prescriptionRecord);
                }
            }
        }
        //检验报告
        if (CommonUtils.isNotEmpty(inspectReportRecordList)) {
            for (InspectReportRecordEntity inspectReportRecord : inspectReportRecordList) {
                if (businessType.equals(inspectReportRecord.getBusinessType()) && visitNo.equals(inspectReportRecord.getVisitId())) {
                    inspectReportRecord.setBusinessId(vrInpatientVisitRecord.getHospitalRecordId());
                    inspectReportRecordDAO.update(inspectReportRecord);
                }
            }
        }
    }


    /**
     * @description: 初始化机构的手术类型字典
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/12/31 19:49
     * @param:
     * @return: void
     */

    public void initSurgicalType(String objectId) {
        List<SurgicalType> surgicalTypes = surgicalTypeDAO.querySurgicalTypeList(objectId);

        ParamsOrgQo request = new ParamsOrgQo();
        request.setType(type);
        //查询所有机构
        BaseResponse listBaseResponse = baseDataService.queryOrganizationList(request);
        if (CommonUtils.isNotEmpty(listBaseResponse) && listBaseResponse.getCode() == ResultCode.SUCCESS && null != listBaseResponse.getData()) {
            List<Map> data = (List<Map>) listBaseResponse.getData();
            if (CommonUtils.isNotEmpty(data)) {
                for (Map datum : data) {
                    //机构代码
                    String organizationId = (String) datum.get("organizationId");
                    String orgId = (String) datum.get("orgId");

                    String objId = "";
                    if (Constants.GOL.equals(proSource)) {
                        objId = orgId;
                    } else {
                        objId = organizationId;
                    }
                    SurgicalType newSurgicalType;
                    if (CommonUtils.isNotEmpty(objId)) {
                        //查询是否已经初始化过
                        List<SurgicalType> objSurgicalTypeList = surgicalTypeDAO.querySurgicalTypeList(objId);
                        //未初始化过
                        if (CommonUtils.isEmpty(objSurgicalTypeList)) {
                            if (CommonUtils.isNotEmpty(surgicalTypes)) {
                                for (SurgicalType surgicalType : surgicalTypes) {
                                    newSurgicalType = new SurgicalType();
                                    BeanUtils.copy(surgicalType, newSurgicalType);

                                    newSurgicalType.setSurgicalTypeId(UUID.randomUUID().toString());
                                    newSurgicalType.setOrgId(objId);
                                    surgicalTypeDAO.save(newSurgicalType);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 根据病种配置采集门诊或住院记录
     */

    @DAOTransaction
    @ScheduleJob(jobName = "collectDataByDisease", cron = "0 0 4 * * ?", shardingTotalCount = 1, description =
            "根据病种配置采集门诊或住院记录", overwrite = true)
    public void collectDataByDisease(JobParameter jobParameter) throws ControllerException {

        String tenantId = (String)ContextUtils.get("$tenantId");
        if(null == tenantId){
            ContextUtils.put("$tenantId", SpringPropertiesUtil.get("tenantId"));
        }

        logger.info("===根据病种配置采集数据开始===");
        //1.查询病种信息
        List<QueryDiseaseTypeResponse> diseaseTypeListResponse = diseaseSpeciesService.queryAllDiseaseSpeciesList();
        if (CommonUtils.isEmpty(diseaseTypeListResponse)) {
            logger.info("未查询到病种信息");
            return;
        }
        logger.info("===获取到全部的病种信息===");
        List<String> visitRecordIdList = Lists.newArrayList();
        List<String> inpatientRecordIdList = Lists.newArrayList();
        logger.info("===根据采集数据保存到关联表===");
        for (QueryDiseaseTypeResponse diseaseType : diseaseTypeListResponse) {
            if (CommonUtils.isEmpty(diseaseType.getCollectConfigList())) {
                continue;
            }
            List<DiseaseCollectConfigEntity> visitCollectConfigLit = Lists.newArrayList();
            List<DiseaseCollectConfigEntity> inpatientCollectConfigLit = Lists.newArrayList();
            //1.1获取采集条件信息
            for (DiseaseCollectConfigEntity collectConfig : diseaseType.getCollectConfigList()) {
                if (StringUtils.isEmpty(collectConfig.getCollectValue())) {
                    continue;
                }
                if (Constants.ONE_STRING.equals(collectConfig.getCollectClass())) {
                    //门诊采集配置
                    visitCollectConfigLit.add(collectConfig);
                } else if (Constants.TWO_STRING.equals(collectConfig.getCollectClass())) {
                    //住院采集配置
                    inpatientCollectConfigLit.add(collectConfig);
                }
            }
            //2.获取采集记录
            List<PatientMedicalDataCollectEntity> collectEntityList = Lists.newArrayList();
            //2.1采集门诊记录
            List<PatientMedicalDataCollectEntity> visitCollectEntityList = this.queryCollectDate(Constants.ONE_STRING, visitCollectConfigLit);
            if (CommonUtils.isNotEmpty(visitCollectEntityList)) {
                collectEntityList.addAll(visitCollectEntityList);
            }
            //2.2采集住院记录
            List<PatientMedicalDataCollectEntity> inpatientCollectEntityList = this.queryCollectDate(Constants.TWO_STRING, inpatientCollectConfigLit);
            if (CommonUtils.isNotEmpty(inpatientCollectEntityList)) {
                collectEntityList.addAll(inpatientCollectEntityList);
            }
            //3.保存有效的采集记录
            for (PatientMedicalDataCollectEntity collect : collectEntityList) {
                //记录数据里卡号卡类型为空的不采集
                if (StringUtils.isEmpty(collect.getCardNumber())) {
                    continue;
                }
                //3.1判断记录患者是否入组，没入组不保存
                List<FusTeamChronicGroupRecordEntity> fusTeamChronicGroupRecords = fusTeamChronicGroupRecordDAO.queryChronicGroupByCardAndDiseaseId(diseaseType.getOrganizationId(), collect.getCardType(), collect.getCardNumber(), diseaseType.getDiseaseTypeId());
                if (CommonUtils.isEmpty(fusTeamChronicGroupRecords)) {
                    continue;
                }
                //3.2查找数据是否已采集
                Long count = patientMedicalDataCollectDAO.getCollectDateByDiseaseIdAndRecordIdAndType(diseaseType.getDiseaseTypeId(), collect.getRecordId(), collect.getRecordType());
                //存在不保存
                if (Constants.ZORE < count) {
                    continue;
                }
                collect.setChronicDiseaseId(diseaseType.getDiseaseTypeId());
                collect.setChronicDiseaseName(diseaseType.getDiseaseTypeName());
                collect.setCollectTime(new Date());
                //保存采集关联表
                patientMedicalDataCollectDAO.save(collect);

                Byte routeDetailType = null;
                if (Constants.ONE == collect.getRecordType()) {
                    visitRecordIdList.add(collect.getRecordId());
                    routeDetailType = Byte.valueOf(Constants.ONE_STRING);
                } else {
                    inpatientRecordIdList.add(collect.getRecordId());
                    routeDetailType = Byte.valueOf(Constants.EIGHT.toString());
                }
                //4.判断采集数据是否有相关未执行/待确认的随访计划
                Long followRecordId = patientMedicalDataCollectDAO.queryFollowUpIdByCard(collect.getCardType(), collect.getCardNumber(), routeDetailType, collect.getChronicDiseaseId(), collect.getRecordTime());
                //存在未执行的随访记录则修改状态为待确认
                if (CommonUtils.isNotEmpty(followRecordId)) {
                    followUpRecordsDAO.updateFollowUpStastusById(Byte.valueOf(Constants.TWO_STRING), followRecordId);
                    continue;
                }

                //4.1不存在自动生成随访计划并关联记录
                AddExecutionListRequest request = new AddExecutionListRequest();
                request.setIsNotify(Byte.valueOf(Constants.ZORE_STRING));
                request.setOperatorId(adminUserId);
                request.setAutoCreateFlag(Constants.ONE_STRING);
                request.setFollowUpStatus(Byte.valueOf(Constants.TWO_STRING));
                request.setRouteDetailType(routeDetailType);
                request.setPlanTime(collect.getRecordTime());
                String propertyCode = "";
                if (Constants.ONE == collect.getRecordType()) {
                    propertyCode = "013104";
                } else {
                    propertyCode = "013105";
                }
                try {
                    BasePropertyConfig basePropertyConfig = serviceOpenRpcService.getBasePropertyConfig(propertyCode, diseaseType.getOrganizationId());
                    request.setMedicalRecordId(basePropertyConfig.getPropertyData());
                    request.setMedicalRecordName(basePropertyConfig.getPropertyName());
                } catch (Exception e) {
                    logger.info("获取病历参数失败", e.getMessage());
                }

                DiseaseSpecies diseaseSpecies = new DiseaseSpecies();
                diseaseSpecies.setDiseaseTypeId(diseaseType.getDiseaseTypeId());
                diseaseSpecies.setDiseaseTypeName(diseaseType.getDiseaseTypeName());
                for (FusTeamChronicGroupRecordEntity fusTeamChronicGroupRecord : fusTeamChronicGroupRecords) {
                    FollowUpRecords followUpRecords = followUpPlanService.saveFollowUpRecords(request, diseaseSpecies, fusTeamChronicGroupRecord, null);
                    patientMedicalDataCollectDAO.updateCollectDateFollowRecordId(followUpRecords.getRecordId(), collect.getId());
                }
            }
        }
        logger.info("===根据门诊、住院记录id更新各数据标删除标识为1不可删除===");
        List<String> recordIdList = Lists.newArrayList();
        if (CommonUtils.isNotEmpty(visitRecordIdList)) {
            //更新门诊记录删除标识
            vrOutpatientVisitRecordDAO.updateDeleteFlag(visitRecordIdList);
            recordIdList.addAll(visitRecordIdList);
        }
        if (CommonUtils.isNotEmpty(inpatientRecordIdList)) {
            //更新住院记录删除标识
            vrInpatientVisitRecordDAO.updateDeleteFlag(inpatientRecordIdList);
            recordIdList.addAll(inpatientRecordIdList);
        }

        if (CommonUtils.isNotEmpty(recordIdList)) {
            //更新诊断记录删除标识
            vrVisitDiagnosisDAO.updateDeleteFlag(recordIdList);
            //更新检验报告删除标识
            inspectReportRecordDAO.updateDeleteFlag(recordIdList);
            //更新检查报告删除标识
            examReportDAO.updateDeleteFlag(recordIdList);
            //更新手术记录删除标识
            vrSurgicalRecordDAO.updateDeleteFlag(recordIdList);
            //更新处置(治疗)记录删除标识
            treatmentRecordDAO.updateDeleteFlag(recordIdList);
            //更新处方(用药)记录删除标识
            prescriptionRecordDAO.updateDeleteFlag(recordIdList);
        }
        logger.info("===根据病种配置采集数据结束===");
    }

    /**
     * 订阅病例定时执行
     */

    @ScheduleJob(jobName = "subscribePatientInfoTask", cron = "0 0 07 * * ?", shardingTotalCount = 1, description =
            "同步订阅病历数据", overwrite = true)
    public void subscribePatientInfoTask(JobParameter jobParameter) {

        String tenantId = (String)ContextUtils.get("$tenantId");
        if(null == tenantId){
            ContextUtils.put("$tenantId", SpringPropertiesUtil.get("tenantId"));
        }

        try {
            //1.获取所有订阅病例信息
            List<ListPatientSearchRuleResponse> searchRuleResponses = patientSearchRuleDAO.queryPatientSubscribeInfo();
            if (CommonUtils.isNotEmpty(searchRuleResponses)) {
                for (ListPatientSearchRuleResponse patientSearchRule : searchRuleResponses) {
                    //TODO 订阅的规则，定时执行获取当前日期前7天的数据
                    long patientSearchRuleId = Long.parseLong(patientSearchRule.getPatientSearchRuleId());
                    List<PatientSearchRuleDetail> patientSearchRuleDetails = patientSearchRuleDetailDAO.queryByPatientSearchRuleId(patientSearchRuleId);
                    Integer dateValue = 7;
                    for (PatientSearchRuleDetail patientSearchRuleDetail : patientSearchRuleDetails) {
                        BasePropertyConfig basePropertyConfig = basePropertyConfigService.getPropertyConfigByPropertyCode("013108", "hzsdsrmyy");
                        if (CommonUtils.isNotEmpty(basePropertyConfig)) {
                            dateValue = Integer.valueOf(basePropertyConfig.getPropertyData());
                        }
                        if (RuleConditionTypeEnum.RECORD_TIME.getType() == patientSearchRuleDetail.getRuleConditionType()) {
                            //更新记录时间
                            Date date = new Date();
                            patientSearchRuleDetail.setStartDate(DateUtil.dateAddDay(date, -dateValue));
                            patientSearchRuleDetail.setEndDate(date);
                        }
                    }
                    PatientSearchRuleRequest request = new PatientSearchRuleRequest();
                    request.setPatientSearchRuleId(patientSearchRuleId);
                    //刷新病历数量
                    patientSearchRuleExecuteService.refreshResult(request);
                }
            }
        } catch (Exception e) {
            logger.info("定时更新订阅病历失败", e.getMessage());
        }
    }

    /**
     * 订阅病历消息推送
     */

//    @ScheduleJob(jobName = "subscribePatientPushTask", cron = "0 0 20 * * ?", shardingTotalCount = 1, description =
//            "订阅病历消息推送", overwrite = true)
    public void subscribePatientPushTask(JobParameter jobParameter) {

        String tenantId = (String) ContextUtils.get("$tenantId");
        if(null == tenantId){
            ContextUtils.put("$tenantId", SpringPropertiesUtil.get("tenantId"));
        }

        try {
            //1.查询订阅病历数量
            List<ListSubscribeResponse> listSubscribeResponses = patientSearchRuleDAO.listSubscribe();
            if (CommonUtils.isNotEmpty(listSubscribeResponses)) {
                for (ListSubscribeResponse listSubscribeResponse : listSubscribeResponses) {
                    //2.订阅未读数量>0 执行消息发送
                    if (listSubscribeResponse.getUnreadCount() > 0) {
                        //3.消息发送
                        PushMessageRequest pushMessageRequest = new PushMessageRequest();
                        //3.1.配置模板信息
                        pushMessageRequest.setTemplateCode(MsgTemplateCode.SUBSCRIBE_MEDICAL_REMIND.getCode());
                        pushMessageRequest.setNotificateType(String.valueOf(NotificationEvent.NotificateType.subscribe_medical_remind));
                        pushMessageRequest.setRoleId("doctor");
                        pushMessageRequest.setUserId(listSubscribeResponse.getCreateUserId());
                        //3.2.配置消息内容
                        Map<String, String> variableMap = new HashMap<>();
                        variableMap.put("jiguang", "极光消息");
                        variableMap.put("#病例数量#", listSubscribeResponse.getUnreadCount().toString());
                        variableMap.put("#条件名称#", listSubscribeResponse.getRuleName());
                        pushMessageRequest.setMsgVariableMap(variableMap);
                        sendMsgService.pushNewMessage(pushMessageRequest);
                    }
                }
            }
        } catch (Exception e) {
            logger.info("定时发送订阅病历信息失败：" + e.getMessage());
        }
    }

    private List<PatientMedicalDataCollectEntity> queryCollectDate(String collectClass, List<DiseaseCollectConfigEntity> collectConfigList) {
        List<String> departmentIdList = Lists.newArrayList();
        List<String> diagnosisList = Lists.newArrayList();
        List<String> indexList = Lists.newArrayList();
        List<String> operateList = Lists.newArrayList();
        List<String> operativeList = Lists.newArrayList();
        List<String> drugList = Lists.newArrayList();
        for (DiseaseCollectConfigEntity collectConfig : collectConfigList) {
            String[] collectValues = collectConfig.getCollectValue().split(",");
            if (DiseaseCollectConditionEnum.DEPTMENT.getType().equals(collectConfig.getCollectCondition())) {
                for (String value : collectValues) {
                    departmentIdList.add(value);
                }
            }
            if (DiseaseCollectConditionEnum.DIAGNOSIS.getType().equals(collectConfig.getCollectCondition())) {
                for (String value : collectValues) {
                    diagnosisList.add(value);
                }
            }
            if (DiseaseCollectConditionEnum.INDEX.getType().equals(collectConfig.getCollectCondition())) {
                for (String value : collectValues) {
                    indexList.add(value);
                }
            }
            if (DiseaseCollectConditionEnum.OPERATE.getType().equals(collectConfig.getCollectCondition())) {
                for (String value : collectValues) {
                    operateList.add(value);
                }
            }
            if (DiseaseCollectConditionEnum.OPERATIVE.getType().equals(collectConfig.getCollectCondition())) {
                for (String value : collectValues) {
                    operativeList.add(value);
                }
            }
            if (DiseaseCollectConditionEnum.DRUG.getType().equals(collectConfig.getCollectCondition())) {
                for (String value : collectValues) {
                    drugList.add(value);
                }
            }
        }
        return vrOutpatientVisitRecordDAO.queryPatientDataList(collectClass, departmentIdList, diagnosisList, indexList, operateList, operativeList, drugList);
    }


}
